package com.spice.im.attendance;

import java.io.File;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Calendar;
import java.util.Date;
import java.util.HashMap;
import java.util.Iterator;
import java.util.LinkedList;
import java.util.List;
import java.util.Map;
import java.util.UUID;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;
import java.util.regex.Matcher;
import java.util.regex.Pattern;

import me.maxwin.view.XListViewHeader;

import org.jivesoftware.smack.packet.IQ;
import org.jivesoftware.smack.packet.Packet;
import org.jivesoftware.smack.util.StringUtils;

import baidumapsdk.demo.BaiduMapUtilByRacer;
import baidumapsdk.demo.LocationBean;
import baidumapsdk.demo.BaiduMapUtilByRacer.LocateListener;
import cn.finalteam.galleryfinal.GalleryHelper;
import cn.finalteam.galleryfinal.GalleryImageLoader;
import cn.finalteam.galleryfinal.PhotoCropActivity;
import cn.finalteam.galleryfinal.model.PhotoInfo;
import cn.finalteam.toolsfinal.BitmapUtils;
import cn.finalteam.toolsfinal.DateUtils;
import cn.finalteam.toolsfinal.DeviceUtils;
import cn.finalteam.toolsfinal.FileUtils;
import cn.finalteam.toolsfinal.Logger;

import com.lidroid.xutils.HttpUtils;
import com.lidroid.xutils.exception.HttpException;
import com.lidroid.xutils.http.HttpHandler;
import com.lidroid.xutils.http.RequestParams;
import com.lidroid.xutils.http.ResponseInfo;
import com.lidroid.xutils.http.callback.RequestCallBack;
import com.lidroid.xutils.http.client.HttpRequest;
import com.speed.im.login.EncryptionUtil;
import com.spice.im.BaseDialog;
import com.spice.im.ContactFrameActivity;
import com.spice.im.FlippingLoadingDialog;
import com.spice.im.MainActivity;
import com.spice.im.R;
import com.spice.im.SpiceApplication;
import com.spice.im.ContactFrameActivity.ContactGroupListOnClick;
import com.spice.im.chat.ChatPullRefListActivity;
import com.spice.im.preference.PreferenceActivity;
import com.spice.im.preference.PreferenceActivity.exPhoneCallListener;
import com.spice.im.utils.ConstantValues;
//import com.spice.im.ContactFrameActivity.CustomListAdapter;
//import com.spice.im.RegisterActivity;
//import com.spice.im.chat.ChatPullRefListActivity;
//import com.spice.im.chat.MessageText;
//import com.spice.im.group.MucCreateIQ;
//import com.spice.im.group.MucCreateIQResponse;
//import com.spice.im.group.MucCreateIQResponseProvider;
import com.spice.im.utils.DialogUtil;
import com.spice.im.utils.HeaderLayout;
import com.spice.im.utils.HeaderLayout.onMiddleImageButtonClickListener;
import com.spice.im.utils.TextUtils;
import com.spice.im.utils.HeaderLayout.HeaderStyle;
import com.spice.im.utils.HeaderLayout.onRightImageButtonClickListener;
import com.spice.im.utils.MyDialog.MyDialogListener;
import com.spice.im.utils.MyDialog;
import com.spice.im.utils.MyDialogPopWinSelect;
import com.stb.core.chat.ContactGroup;
import com.stb.isharemessage.BeemApplication;
import com.stb.isharemessage.IConnectionStatusCallback;
import com.stb.isharemessage.service.XmppConnectionAdapter;
import com.stb.isharemessage.service.aidl.IXmppFacade;
import com.dodola.model.GreetInfo;
import com.dodola.model.UnReadMsgNumber;
import com.dodowaterfall.widget.FlowView;
//import com.example.android.bitmapfun.util.AsyncTask;
import com.beem.push.utils.AsyncTask;
import com.handmark.pulltorefresh.library.PullToRefreshBase;
import com.handmark.pulltorefresh.library.PullToRefreshListView;
import com.handmark.pulltorefresh.library.PullToRefreshBase.Mode;
import com.handmark.pulltorefresh.library.PullToRefreshBase.OnRefreshListener2;
import com.stb.isharemessage.utils.BeemBroadcastReceiver;
import com.stb.isharemessage.utils.BeemConnectivity;

import android.app.Activity;
import android.app.AlertDialog;
//import android.app.AlertDialog;
import android.app.Dialog;
import android.content.BroadcastReceiver;
import android.content.ComponentName;
import android.content.ContentResolver;
import android.content.ContentValues;
import android.content.Context;
import android.content.DialogInterface;
import android.content.Intent;
import android.content.IntentFilter;
import android.content.ServiceConnection;
import android.content.SharedPreferences;
import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import android.net.ConnectivityManager;
import android.net.Uri;
import android.os.Bundle;
import android.os.Environment;
import android.os.Handler;
import android.os.IBinder;
import android.os.Message;
import android.os.RemoteException;
import android.preference.PreferenceManager;
import android.provider.MediaStore;
import android.telephony.PhoneStateListener;
import android.telephony.TelephonyManager;
import android.util.DisplayMetrics;
import android.util.Log;
import android.view.Gravity;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.view.Window;
import android.view.View.OnClickListener;
import android.view.WindowManager;
//import android.widget.Button;
//import android.widget.CheckBox;
//import android.widget.EditText;
//import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.AbsListView.RecyclerListener;
import android.widget.AdapterView.OnItemClickListener;
import android.widget.PopupWindow.OnDismissListener;
import android.widget.AdapterView;
import android.widget.BaseAdapter;
import android.widget.Filter;
import android.widget.Filterable;
import android.widget.ImageView;
import android.widget.ListView;
import android.widget.ProgressBar;
import android.widget.RelativeLayout;
import android.widget.TextView;
import android.widget.Toast;

import com.spice.im.ui.BadgeView;
import com.spice.im.ui.HandyTextView;
import com.spice.im.ui.IGpsFilterCallback;
//import com.spice.im.ui.NearByPopupWindow;
import com.spice.im.ui.BasePopupWindow;
import com.spice.im.ui.BasePopupWindow.onSubmitClickListener;
import com.spice.im.ui.NearByPopupWindow2;

public class AttendanceActivity2 extends Activity implements IGpsFilterCallback,IConnectionStatusCallback,OnClickListener{
	private static ExecutorService LIMITED_TASK_EXECUTOR;
    static {
      LIMITED_TASK_EXECUTOR = (ExecutorService) Executors.newFixedThreadPool(7); 
    }; 
	private static final Intent SERVICE_INTENT = new Intent();
	static {
		SERVICE_INTENT.setComponent(new ComponentName("com.spice.im", "com.stb.isharemessage.BeemService"));
	}
    private static final String TAG = "MucCreateActivity";
    
    private final ServiceConnection mServConn = new BeemServiceConnection();
//    private final BeemBroadcastReceiver mReceiver = new BeemBroadcastReceiver();//原来的网络状态注释掉
    private final OkListener mOkListener = new OkListener();
    
    private final AttendanceRecordListOnClick mOnAttendanceRecordClick = new AttendanceRecordListOnClick();/**单击某条记录*/
    
    protected FlippingLoadingDialog mLoadingDialog;
	private HeaderLayout mHeaderLayout;
	
	private boolean mBinded = false;
    private IXmppFacade mXmppFacade;
	
	private LinearLayout mLayoutSelectPhoto;//定位考勤
	private LinearLayout mLayoutTakePicture;//考勤记录
	
	private CustomListAdapter mAdapter;
//	private CustomListView mListView;
	private PullToRefreshListView ptrlv = null;
	
	
	private XListViewHeader xListViewHeader;
	
	private NearByPopupWindow2 mPopupWindow;
	
	private TextView xlistview_count;
	
	//定位start
	private LocationBean mLocationBean;
	private static Context mContext;
	public double mLongitude;
	public double mLatitude;
	public String mGpsAddr;
	//定位end
	String remarkcode = "";
	HashMap hm_remarkcode = new HashMap();
	
	
    //网络状态start
	private View mNetErrorView;
	private TextView mConnect_status_info;
	private ImageView mConnect_status_btn;
    private exPhoneCallListener myPhoneCallListener = null;
    private TelephonyManager tm = null;
    //网络状态end
	
    public void onCreate(Bundle savedInstanceState) {
    	requestWindowFeature(Window.FEATURE_NO_TITLE);
    	super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_apps);
        this.mContext = this;
        
        DisplayMetrics dm = DeviceUtils.getScreenPix(this);
        mScreenWidth = dm.widthPixels;
        mScreenHeight = dm.heightPixels;
        
    	mHeaderLayout = (HeaderLayout) findViewById(R.id.login_header);
//    	mHeaderLayout.init(HeaderStyle.DEFAULT_TITLE);
    	mHeaderLayout.init(HeaderStyle.TITLE_CHAT);
//    	mHeaderLayout.setDefaultTitle("创建群组", null);
//    	mHeaderLayout.setTitleRightImageButton("定位考勤", null,
//    			R.drawable.return2,
//    			new OnRightImageButtonClickListener());
    	
		mHeaderLayout.setTitleChat(R.drawable.ic_chat_dis_1,
				R.drawable.bg_chat_dis_active, "定位考勤",
				"",
				R.drawable.ic_menu_info,//ic_menu_invite  ic_topbar_profile
				new OnMiddleImageButtonClickListener(),
				R.drawable.return2,
				new OnRightImageButtonClickListener());
		
        mLoadingDialog = new FlippingLoadingDialog(this, "请求提交中");
        
		mLayoutSelectPhoto = (LinearLayout) findViewById(R.id.reg_photo_layout_selectphoto);
		mLayoutTakePicture = (LinearLayout) findViewById(R.id.reg_photo_layout_takepicture);
		mLayoutSelectPhoto.setOnClickListener(mOkListener);
		mLayoutTakePicture.setOnClickListener(mOkListener);
        
        xListViewHeader = (XListViewHeader)findViewById(R.id.xlistview_header);
        xListViewHeader.setVisiableHeight(60);
        xListViewHeader.setState(0);
        xListViewHeader.setVisibility(View.VISIBLE);
        
        xlistview_count = (TextView)findViewById(R.id.xlistview_count);
//        mAdapter = new CustomListAdapter(this, linkedList);
        initRefreshView(linkedList);
        

		initPopupWindow();
		hm_remarkcode.put("0002", "定位考勤失败,hash校验失败");
		hm_remarkcode.put("1000", "考勤失败，用户账户不存在");
		hm_remarkcode.put("2000", "考勤定位成功，考勤时间正常，正常考勤");
		hm_remarkcode.put("3000", "您所在企业定义了考勤区域，考勤定位成功");
		hm_remarkcode.put("4000", "您所在企业定义了考勤区域，您不在考勤区域内，考勤定位失败");
		hm_remarkcode.put("5000", "您所在企业未定义考勤区域，自由签定位成功");
		hm_remarkcode.put("6000", "考勤定位成功，上班未到考勤时间，加班");
		hm_remarkcode.put("7000", "考勤定位成功，上班超过考勤时间，迟到");
		hm_remarkcode.put("8000", "考勤定位成功，下班未到考勤时间，早退");
		hm_remarkcode.put("8888", "您所在企业定义了考勤区域，但允许自由签，自由签定位成功");
		hm_remarkcode.put("9000", "考勤定位成功，下班超过考勤时间，加班");
		hm_remarkcode.put("9997", "定位考勤失败,用户名不允许为空");
		hm_remarkcode.put("9998", "考勤定位成功，参数错误,系统异常,无法检测允许开始、最后打卡时间");
		hm_remarkcode.put("9999", "定位考勤失败,其他系统异常");
//		initDialog();
		
//    	this.registerReceiver(mReceiver, new IntentFilter(BeemBroadcastReceiver.BEEM_CONNECTION_CLOSED));//原来的网络状态注释掉
		
		//网络状态start
        mNetErrorView = findViewById(R.id.net_status_bar_top);
        mConnect_status_info = (TextView)mNetErrorView.findViewById(R.id.net_status_bar_info_top2);
        mConnect_status_btn = (ImageView)mNetErrorView.findViewById(R.id.net_status_bar_btn);
        mConnect_status_btn.setOnClickListener(this);
        
	    IntentFilter mFilter = new IntentFilter();
	    mFilter.addAction(ConnectivityManager.CONNECTIVITY_ACTION); // 添加接收网络连接状态改变的Action
	    registerReceiver(mNetWorkReceiver, mFilter);
        /* 添加自己实现的PhoneStateListener */
        myPhoneCallListener = new exPhoneCallListener();
       
       /* 取得电话服务 */
        tm =(TelephonyManager) this.getSystemService(Context.TELEPHONY_SERVICE);
       
        /* 注册电话通信Listener */
        tm.listen(myPhoneCallListener,PhoneStateListener.LISTEN_CALL_STATE);
	    //网络状态end
        
        SpiceApplication.getInstance().addActivity(this);
    	
    }
	public void onClick(View v) {
		switch (v.getId()) {
		//网络设置
        case R.id.net_status_bar_btn:
			setNetworkMethod(this);
		break;
		}
	}
    @Override
    protected void onResume() {
		super.onResume();
		if (!mBinded){
		    mBinded = getApplicationContext().bindService(SERVICE_INTENT, mServConn, BIND_AUTO_CREATE);	    
		}
    }
    @Override
    protected void onStart() {
		super.onStart();
    }
    /**
     * {@inheritDoc}
     */
    @Override
    protected void onPause() {
		super.onPause();
		
    }
    @Override
    protected void onDestroy() {
		super.onDestroy();
		
		if(mPopupWindow!=null){
			mPopupWindow.unRegisterGpsFilterCallback();
			mPopupWindow = null;
		}
//		mBackDialog.dismiss();
		if(dialog!=null)
			dialog.dismiss();
		dialog = null;
		if(dialog2!=null)
			dialog2.dismiss();
		dialog2 = null;
//		BaiduMapUtilByRacer.stopAndDestroyLocate();
		clearAsyncTask();
//		loadingView.isStop = true;
	    try{//网络状态相关
		    if(mXmppFacade!=null && mXmppFacade.getXmppConnectionAdapter()!=null)
		    	mXmppFacade.getXmppConnectionAdapter().unRegisterConnectionStatusCallback();
	    }catch (RemoteException e) {
	    	e.printStackTrace();
	    }
		if (mBinded) {
			getApplicationContext().unbindService(mServConn);
		    mBinded = false;
		}
		//网络状态start
		unregisterReceiver(mNetWorkReceiver); // 删除广播
		if(tm!=null){
			tm.listen(myPhoneCallListener,PhoneStateListener.LISTEN_NONE);//取消监听即可
			tm = null;
		}
		if(myPhoneCallListener!=null)
			myPhoneCallListener = null;
		//网络状态end
		mXmppFacade = null;
//		this.unregisterReceiver(mReceiver);//原来的网络状态注释掉
		mLocationBean = null;
		System.gc();
		Log.e(TAG, "onDestroy activity");
		
    }
    
    protected List<AsyncTask<Void, Void, Boolean>> mAsyncTasks = new ArrayList<AsyncTask<Void, Void, Boolean>>();
	protected void putAsyncTask(AsyncTask<Void, Void, Boolean> asyncTask) {
		mAsyncTasks.add(asyncTask.executeOnExecutor(LIMITED_TASK_EXECUTOR, null));
	}

	protected void clearAsyncTask() {
		Iterator<AsyncTask<Void, Void, Boolean>> iterator = mAsyncTasks
				.iterator();
		while (iterator.hasNext()) {
			AsyncTask<Void, Void, Boolean> asyncTask = iterator.next();
			if (asyncTask != null && !asyncTask.isCancelled()) {
				asyncTask.cancel(true);
			}
		}
		mAsyncTasks.clear();
	}		    
	protected void showLoadingDialog(String text) {
		if (text != null) {
			mLoadingDialog.setText(text);
		}
		mLoadingDialog.show();
	}

	protected void dismissLoadingDialog() {
		if (mLoadingDialog.isShowing()) {
			mLoadingDialog.dismiss();
		}
	}

	/** 显示自定义Toast提示(来自String) **/
	protected void showCustomToast(String text) {
		View toastRoot = LayoutInflater.from(AttendanceActivity2.this).inflate(
				R.layout.common_toast, null);
		((HandyTextView) toastRoot.findViewById(R.id.toast_text)).setText(text);
		Toast toast = new Toast(AttendanceActivity2.this);
		toast.setGravity(Gravity.CENTER, 0, 0);
		toast.setDuration(Toast.LENGTH_SHORT);
		toast.setView(toastRoot);
		toast.show();
	}
	protected class OnMiddleImageButtonClickListener implements
	onMiddleImageButtonClickListener {

		@Override
		public void onClick() {
			mPopupWindow
			.showViewTopCenter(findViewById(R.id.layout_right));
		}
	}
	private class OnRightImageButtonClickListener implements
	onRightImageButtonClickListener {
	
		@Override
		public void onClick() {
			startActivity(new Intent(AttendanceActivity2.this, ContactFrameActivity.class));//ContactListPullRefListActivity
			AttendanceActivity2.this.finish();
			
//			mPopupWindow
//			.showViewTopCenter(findViewById(R.id.layout_right));
			
//			if(dialog3!=null)
//				dialog3.dismiss();
//			dialog3 =null;		
//			dialog3 = DialogUtil.getMyDialogPopWinSelect("开始考勤",
//							"请选择考勤班段",
//							AttendanceActivity.this, new MyDialogPopWinSelect.MyDialogListener() {
//								
//								@Override
//								public void onPositiveClick(Dialog dialog, View view) {
////									upload2share(age);
//									AttendanceClassSection aClassSection = ((MyDialogPopWinSelect)dialog3).getSelectValue();
////									Toast.makeText(AttendanceActivity.this, "1选中的班次为：" + aClassSection.getOnoffdutyname() + aClassSection.getId(), Toast.LENGTH_SHORT).show();
//								    
//								    
//									mtype = "0";//0 该班段上班考勤时间,1 该班段下班考勤时间
//									time1 = aClassSection.getStarttime1();
//									time2 = aClassSection.getStarttime2();
//									attendancesectionid = aClassSection.getId();
//								    
//									if(dialog!=null)
//										dialog.dismiss();
//									dialog = null;
//									if(dialog2!=null)
//										dialog2.dismiss();
//									dialog2 = null;
//									dialog = DialogUtil.getNewWaitDialog("正在定位考勤...",AttendanceActivity.this);
//									dialog.show();//分享中
//									locate();
//								}
//								
//								@Override
//								public void onNegativeClick(Dialog dialog, View view) {
//									AttendanceClassSection aClassSection = ((MyDialogPopWinSelect)dialog3).getSelectValue();
////									Toast.makeText(AttendanceActivity.this, "2选中的班次为：" + aClassSection.getOnoffdutyname() + aClassSection.getId(), Toast.LENGTH_SHORT).show();
//								    
//									mtype = "1";//0 该班段上班考勤时间,1 该班段下班考勤时间
//									time1 = aClassSection.getEndtime1();
//									time2 = aClassSection.getEndtime2();
//									attendancesectionid = aClassSection.getId();
//								    
//									if(dialog!=null)
//										dialog.dismiss();
//									dialog = null;
//									if(dialog2!=null)
//										dialog2.dismiss();
//									dialog2 = null;
//									dialog = DialogUtil.getNewWaitDialog("正在定位考勤...",AttendanceActivity.this);
//									dialog.show();//分享中
//									locate();
//								}
//							}, MyDialog.ButtonBoth, aClassSections);
//			dialog3.show();
		}
	}
	
    /**
     * The service connection used to connect to the Beem service.
     */
    private class BeemServiceConnection implements ServiceConnection {
		/**
		 * Constructor.
		 */
		public BeemServiceConnection() {
		}
	
		@Override
		public void onServiceConnected(ComponentName name, IBinder service) {
		    mXmppFacade = IXmppFacade.Stub.asInterface(service);
		    if(mXmppFacade!=null){
		    	mBinded = true;//20130804 added by allen
		    	try{
		    		mXmppFacade.getXmppConnectionAdapter().registerConnectionStatusCallback(AttendanceActivity2.this);//网络状态相关
		    	}catch(Exception e){}
		    	Date dNow = new Date();   //当前时间
		    	Date dBefore = new Date();
		    	Calendar calendar = Calendar.getInstance(); //得到日历
		    	calendar.setTime(dNow);//把当前时间赋给日历
		    	calendar.add(calendar.MONTH, -3);  //设置为前3月
		    	dBefore = calendar.getTime();   //得到前3月的时间

		    	SimpleDateFormat sdf=new SimpleDateFormat("yyyy-MM-dd"); //设置时间格式
		    	String defaultStartDate = sdf.format(dBefore);    //格式化前3月的时间
		    	String defaultEndDate = sdf.format(dNow); //格式化当前时间

		    	System.out.println("前3个月的时间是：" + defaultStartDate);
		    	System.out.println("生成的时间是：" + defaultEndDate);
		    	
		    	getAttendanceList(0,defaultStartDate,defaultEndDate);
		    }
		}
		@Override
		public void onServiceDisconnected(ComponentName name) {
			 try{//网络状态相关
				    if(mXmppFacade!=null && mXmppFacade.getXmppConnectionAdapter()!=null)
				    	mXmppFacade.getXmppConnectionAdapter().unRegisterConnectionStatusCallback();
			    }catch (RemoteException e) {
			    	e.printStackTrace();
			    }
		    mXmppFacade = null;
		    mBinded = false;
		}
    }
    
    private Dialog dialog,dialog2,dialog3;
    /**
     * Listener.
     */
    private class OkListener implements OnClickListener {
	
		/**
		 * Constructor.
		 */
		public OkListener() { }
	
		@Override
		public void onClick(View v) {
			switch (v.getId()) {
				case R.id.reg_photo_layout_selectphoto:
					Date dNow2 = new Date();   //当前时间
	        	    SimpleDateFormat sdf2=new SimpleDateFormat("yyyyMMddhhmmss"); //设置时间格式
			    	String defaultStartDate2 = sdf2.format(dNow2);    //格式化前3月的时间
					procinsid = defaultStartDate2+".jpg";
////					GalleryHelper.openGallerySingle(AttendanceActivity.this, true, new GalleryImageLoader());
////					mHandler.sendEmptyMessage(4);
////					mBackDialog.show();
//					if(dialog!=null)
//						dialog.dismiss();
//					dialog = null;
//					if(dialog2!=null)
//						dialog2.dismiss();
//					dialog2 = null;
//					dialog = DialogUtil.getNewWaitDialog("正在定位考勤...",AttendanceActivity.this);
//					dialog.show();//分享中
//					locate();
					
					if(dialog3!=null)
						dialog3.dismiss();
					dialog3 =null;		
					dialog3 = DialogUtil.getMyDialogPopWinSelect("开始考勤",
									"",//请选择考勤班段
									AttendanceActivity2.this, new MyDialogPopWinSelect.MyDialogListener() {
										
										@Override
										public void onPositiveClick(Dialog dialog, View view) {
//											upload2share(age);
											if(((MyDialogPopWinSelect)dialog3).getSelectValue()!=null){
												if(((MyDialogPopWinSelect)dialog3).getSelectValue() instanceof AttendanceClassSection){
													AttendanceClassSection aClassSection = (AttendanceClassSection)(((MyDialogPopWinSelect)dialog3).getSelectValue());
		//											Toast.makeText(AttendanceActivity.this, "1选中的班次为：" + aClassSection.getOnoffdutyname() + aClassSection.getId(), Toast.LENGTH_SHORT).show();
												    
												    
													mtype = "0";//0 该班段上班考勤时间,1 该班段下班考勤时间
													time1 = aClassSection.getStarttime1();
													time2 = aClassSection.getStarttime2();
													attendancesectionid = aClassSection.getId();
												    if(attendancesectionid.equalsIgnoreCase("00000000000000000000000000000000")){
												    	if(((MyDialogPopWinSelect)dialog3).getUploadStatus())
												    		kaoqin();
												    	else
												    		Toast.makeText(AttendanceActivity2.this, "自由签需拍摄工作照片.", Toast.LENGTH_SHORT).show();
												    }else
													     kaoqin();
												}else{
													mtype = "0";
													time1 = "00:00:00";
													time2 = "00:00:00";
													startdate1 = "00:00:00";
													enddate1 = "00:00:00";
													isweekend = "9";
													alternaterule = "9";
													attendanceruleid = "00000000000000000000000000000000";
													attendanceshiftid = "00000000000000000000000000000000";
													attendancesectionid = "00000000000000000000000000000000";
//													kaoqin();
													if(((MyDialogPopWinSelect)dialog3).getUploadStatus())
											    		kaoqin();
											    	else
											    		Toast.makeText(AttendanceActivity2.this, "自由签需拍摄工作照片.", Toast.LENGTH_SHORT).show();
												}
											}else{
												Toast.makeText(AttendanceActivity2.this, "未选择考勤班次!", Toast.LENGTH_SHORT).show();
												
											}
										}
										
										@Override
										public void onNegativeClick(Dialog dialog, View view) {
											if(((MyDialogPopWinSelect)dialog3).getSelectValue()!=null){
												if(((MyDialogPopWinSelect)dialog3).getSelectValue() instanceof AttendanceClassSection){
													AttendanceClassSection aClassSection = (AttendanceClassSection)(((MyDialogPopWinSelect)dialog3).getSelectValue());
		//											Toast.makeText(AttendanceActivity.this, "2选中的班次为：" + aClassSection.getOnoffdutyname() + aClassSection.getId(), Toast.LENGTH_SHORT).show();
												    
													mtype = "1";//0 该班段上班考勤时间,1 该班段下班考勤时间
													time1 = aClassSection.getEndtime1();
													time2 = aClassSection.getEndtime2();
													attendancesectionid = aClassSection.getId();
												    
//													kaoqin();
													if(attendancesectionid.equalsIgnoreCase("00000000000000000000000000000000")){
												    	if(((MyDialogPopWinSelect)dialog3).getUploadStatus())
												    		kaoqin();
												    	else
												    		Toast.makeText(AttendanceActivity2.this, "自由签需拍摄工作照片.", Toast.LENGTH_SHORT).show();
												    }else
													     kaoqin();
												}else{
													mtype = "1";
													time1 = "00:00:00";
													time2 = "00:00:00";
													startdate1 = "00:00:00";
													enddate1 = "00:00:00";
													isweekend = "9";
													alternaterule = "9";
													attendanceruleid = "00000000000000000000000000000000";
													attendanceshiftid = "00000000000000000000000000000000";
													attendancesectionid = "00000000000000000000000000000000";
//													kaoqin();
													if(((MyDialogPopWinSelect)dialog3).getUploadStatus())
											    		kaoqin();
											    	else
											    		Toast.makeText(AttendanceActivity2.this, "自由签需拍摄工作照片.", Toast.LENGTH_SHORT).show();
												}
											}else{
												Toast.makeText(AttendanceActivity2.this, "未选择考勤班次!", Toast.LENGTH_SHORT).show();
												
											}
										}
									}, MyDialog.ButtonBoth, aClassSections,CurrentUid,procinsid);//procinsid即为考勤图片名称前缀
					dialog3.show();
					
					break;
	
				case R.id.reg_photo_layout_takepicture:
//					takePhotoAction();
					
			    	Date dNow = new Date();   //当前时间
			    	Date dBefore = new Date();
			    	Calendar calendar = Calendar.getInstance(); //得到日历
			    	calendar.setTime(dNow);//把当前时间赋给日历
			    	calendar.add(calendar.MONTH, -3);  //设置为前3月
			    	dBefore = calendar.getTime();   //得到前3月的时间

			    	SimpleDateFormat sdf=new SimpleDateFormat("yyyy-MM-dd"); //设置时间格式
			    	String defaultStartDate = sdf.format(dBefore);    //格式化前3月的时间
			    	String defaultEndDate = sdf.format(dNow); //格式化当前时间

			    	System.out.println("前3个月的时间是：" + defaultStartDate);
			    	System.out.println("生成的时间是：" + defaultEndDate);
			    	
			    	getAttendanceList(0,defaultStartDate,defaultEndDate);//ConstantValues.refresh
				break;
			}
	
		}
    };
    
    public void kaoqin(){
    	if(dialog!=null)
			dialog.dismiss();
		dialog = null;
		if(dialog2!=null)
			dialog2.dismiss();
		dialog2 = null;
		dialog = DialogUtil.getNewWaitDialog("正在定位考勤...",AttendanceActivity2.this);
		dialog.show();//分享中
		locate();
    }
    
    //0002 false(hash校验失败)
	//0001 考勤失败，用户账户不存在
	//0003 定义了考勤区域，考勤成功
	//0004 定义了考勤区域，考勤失败 
	//0005 未定义考勤区域，自由签成功
	//9998 用户名不允许为空
	//9999 其他错误
	private String[] errorMsg = new String[]{"定位考勤成功.",
			"服务连接中1-1,请稍候再试.",
			"服务连接中1-2,请稍候再试.",
			"服务连接中1-3,请稍候再试.",
			"网络连接不可用,请检查你的网络设置.",
			"系统错误.定位考勤失败.",//9999
			"定义了考勤区域，考勤成功.",//0003
			"定位考勤失败,hash校验失败",//0002
			"考勤失败，用户账户不存在",//0001
			"定义了考勤区域，考勤失败",//0004
			"未定义考勤区域，自由签成功",//0005
			"用户名不允许为空",//9998
			"",
			"抱歉,没有找到相关结果.",
			"请求异常,稍候重试!"
			};
	private int errorType = 5;
	

	
    private void initCreate(String mgpsaddr,
    		String mlongitude,
    		String mlatitude,
    		String mtype,
    		String time1,
    		String time2,
    		String attendancesectionid,
    		String procinsid
    		){
		try{
			if(BeemConnectivity.isConnected(getApplicationContext())){
		    if(mXmppFacade!=null 
					&& mXmppFacade.getXmppConnectionAdapter()!=null 
					&& mXmppFacade.getXmppConnectionAdapter().getAdaptee()!=null//&& !mXmppFacade.getXmppConnectionAdapter().getAdaptee().isAuthenticated()
					&& mXmppFacade.getXmppConnectionAdapter().getAdaptee().isConnected()
					&& mXmppFacade.getXmppConnectionAdapter().getAdaptee().isAuthenticated()
					&& mXmppFacade.getXmppConnectionAdapter().getAdaptee().isAlive()
					){
		    	AttendanceIQ reqXML = new AttendanceIQ();
	            reqXML.setId("1234567890");
	            reqXML.setApikey("abcdefghijklmnopqrstuvwxyz");
	            reqXML.setUid(StringUtils.parseBareAddress2(mXmppFacade.getXmppConnectionAdapter().getJID()));//2
	            SharedPreferences settings = PreferenceManager.getDefaultSharedPreferences(this);
	    	    String username = settings.getString(BeemApplication.ACCOUNT_USERNAME_KEY, "");
	            reqXML.setUsername(username);
	            
	            reqXML.setMgpsaddr(mgpsaddr);
	            reqXML.setMlongitude(mlongitude);
	            reqXML.setMlatitude(mlatitude);
	            
	            reqXML.setMtype(mtype);//0 该班段上班考勤时间,1 该班段下班考勤时间
	            reqXML.setTime1(time1);//格式 HH:mm:ss 允许开始打卡时间
	            reqXML.setTime2(time2);//格式 HH:mm:ss 允许最后打卡时间
	            reqXML.setAttendanceruleid(attendanceruleid);//考勤规则id
	            reqXML.setAttendanceshiftid(attendanceshiftid);//考勤班次id （一天之内考勤的班段组合）
	            reqXML.setAttendancesectionid(attendancesectionid);//考勤班段id
	            
	            reqXML.setStartdate(startdate1);//本考勤规则起始日期
	            reqXML.setEnddate(enddate1);//本考勤规则结束日期
	            reqXML.setIsweekend(isweekend);//(休息日是否上班：周六班0，周日班1，周六日都班2，周末休息3),
	            reqXML.setAlternaterule(alternaterule);//（轮换规则：按天0，按周1，按半月2，按月3，按季度4，按半年5，按年轮换6，不轮换7）
	            if(attendanceruleid.equalsIgnoreCase("00000000000000000000000000000000"))
	            	reqXML.setProcinsid(procinsid);
	            else
	            	reqXML.setProcinsid("0");
	            String uuid = mXmppFacade.getXmppConnectionAdapter().getAdaptee().getUUID(this,username);
	            reqXML.setUuid(uuid);
//	            String hashcode = "";//apikey+view+orderby+uuid 使用登录成功后返回的sessionid作为密码做3des运算
	            String hash_dest_src = "abcdefghijklmnopqrstuvwxyz"+ StringUtils.parseBareAddress2(mXmppFacade.getXmppConnectionAdapter().getJID())+uuid;
	            String hash_dest = EncryptionUtil.getHash2(hash_dest_src, "SHA");
	            reqXML.setHashcode(hash_dest);
	            reqXML.setType(IQ.Type.SET);
	            String elementName = "attendanceiq"; 
	    		String namespace = "com:isharemessage:attendanceiq";
	    		AttendanceIQResponseProvider provider = new AttendanceIQResponseProvider();
	            Packet rt =  mXmppFacade.getXmppConnectionAdapter().excute(reqXML, "attendanceiq", "com:isharemessage:attendanceiq", provider);
	            
	            if(rt!=null){
	                if (rt instanceof AttendanceIQResponse) {
	                	final AttendanceIQResponse attendanceIQResponse = (AttendanceIQResponse) rt;

	                    if (attendanceIQResponse.getChildElementXML().contains(
	                            "com:isharemessage:attendanceiq")) {
//	    					MainActivity.this.runOnUiThread(new Runnable() {
//		                    	
//    							@Override
//    							public void run() {
//    								showCustomToast("服务器应答消息："+contactGroupListIQResponse.toXML().toString());
//    							}
//    						});
	                        String Id = attendanceIQResponse.getId();
	                        String Apikey = attendanceIQResponse.getApikey();
	                        String retcode = attendanceIQResponse.getRetcode();
	                        remarkcode = retcode;
	                        String memo = attendanceIQResponse.getMemo();
	                        if(retcode.equalsIgnoreCase("0001"))
	                        	errorType = 8;
	                        else if(retcode.equalsIgnoreCase("0002"))
	                        	errorType = 7;
	                        else if(retcode.equalsIgnoreCase("0003"))
	                        	errorType = 6;
	                        else if(retcode.equalsIgnoreCase("0004"))
	                        	errorType = 9;
	                        else if(retcode.equalsIgnoreCase("0005"))
	                        	errorType = 10;
	                        else if(retcode.equalsIgnoreCase("9998"))
	                        	errorType = 11;
	                        else
	                        	errorType = 5;
	                        return;
	                    }
	                } 
	            }
	    		errorType = 1;
		    }else
		    	errorType = 1;
		    
			}else
				errorType = 4;
		}catch(RemoteException e){
			e.printStackTrace();
			errorType = 2;
		}catch(Exception e){
			e.printStackTrace();
			errorType = 3;
		}
    }
	private void startCreate(final String mgpsaddr,
			final String mlongitude,
			final String mlatitude,
			final String mtype,
    		final String time1,
    		final String time2,
    		final String attendancesectionid,
    		final String procinsid) {

		putAsyncTask(new AsyncTask<Void, Void, Boolean>() {

			@Override
			protected void onPreExecute() {
				super.onPreExecute();
//				showLoadingDialog("正在加载,请稍后...");
			}

			@Override
			protected Boolean doInBackground(Void... params) {
//				initContactList();
				initCreate(mgpsaddr,mlongitude,mlatitude,mtype,
			    		time1,
			    		time2,
			    		attendancesectionid,
			    		procinsid);
				return true;
			}

			@Override
			protected void onPostExecute(Boolean result) {
				super.onPostExecute(result);
//				dismissLoadingDialog();
//				if (!result) {
////					showCustomToast("数据加载失败...");
					mHandler.sendEmptyMessage(10);
//				} else {
//					mHandler.sendEmptyMessage(11);
//				}
//				ptrstgv.getRefreshableView().hideFooterView();
			}

		});
	}
	Handler mHandler = new Handler() {

		@Override
		public void handleMessage(android.os.Message msg) {
			super.handleMessage(msg);
			switch (msg.what) {
			case 0:
				if(errorType!=5)
					showCustomToast(errorMsg[errorType]);
				else{
					showCustomToast("群聊创建成功!");
					startActivity(new Intent(AttendanceActivity2.this, ContactFrameActivity.class));//ContactListPullRefListActivity
					finish();	
				}
				break;

			case 1:
				
//				progress.setText(msg.arg1+"%");//20150831 第三种方法
//				bar.setProgress(msg.arg1);//20150831 第三种方法
				//progress.setText(msg.arg1);//20150831 第三种方法
				progress.setText("100%");
				progressMainText.setText("考勤成功:"+mGpsAddr+";mLongitude="+mLongitude+";mLatitude="+mLatitude);
				bar.setProgress(100);//20150831 第三种方法
				break;
			case 2:
				progress.setText("100%");//20150831 第三种方法
				bar.setProgress(100);//20150831 第三种方法
				
				creatingProgress.dismiss();
//				transformfilepath = 
				if(transformfilepath.lastIndexOf("/")!=-1)
					transformfilepath = XmppConnectionAdapter.downloadPrefix+"9999"+"/"+transformfilepath.substring(transformfilepath.lastIndexOf("/")+1);
				else
					transformfilepath = XmppConnectionAdapter.downloadPrefix+"9999"+"/"+transformfilepath;
				break;
			case 3:
				progress.setText("上传失败!");
				creatingProgress.dismiss();
				break;
			case 4:
				initialProgressDialog();
				creatingProgress.show();
				break;
				
			case 5:
//				mBackDialog.getProgress().setProgress(100);
//				mBackDialog.getHtvMessage().setText(mGpsAddr+";"+mLongitude+";"+mLatitude);
				if(dialog!=null)
				dialog.dismiss();
				dialog = null;
				String msgStr = "考勤结果:" + mGpsAddr +";"+mLongitude+";"+mLatitude;
				if(dialog2!=null)
					dialog2.dismiss();
				dialog2 =null;		
				dialog2 = DialogUtil.getMyDialog("考勤成功",
								msgStr,
								AttendanceActivity2.this, new MyDialogListener() {
									
									@Override
									public void onPositiveClick(Dialog dialog, View view) {
//										upload2share(age);
									}
									
									@Override
									public void onNegativeClick(Dialog dialog, View view) {
										
									}
								}, MyDialog.ButtonConfirm);
				dialog2.show();
				break;
			case 6:
//				mBackDialog.getProgress().setProgress(0);
				if(dialog!=null)
				dialog.dismiss();
				dialog = null;
				if(dialog2!=null)
					dialog2.dismiss();
				dialog2 =null;	
				dialog2 = DialogUtil.getMyDialog("考勤失败",
						"定位失败,请稍候重试!",
						AttendanceActivity2.this, new MyDialogListener() {
							
							@Override
							public void onPositiveClick(Dialog dialog, View view) {
//								upload2share(age);
							}
							
							@Override
							public void onNegativeClick(Dialog dialog, View view) {
								
							}
						}, MyDialog.ButtonConfirm);
				dialog2.show();
				break;
			case 7:
//				mBackDialog.getProgress().setProgress(50);
				break;
			case 8://网络连接不可用,请检查你的网络设置.
				if(dialog!=null)
				dialog.dismiss();
				dialog = null;
				if(dialog2!=null)
					dialog2.dismiss();
				dialog2 =null;	
				dialog2 = DialogUtil.getMyDialog("考勤失败",
						"网络连接不可用,请检查你的网络设置.",
						AttendanceActivity2.this, new MyDialogListener() {
							
							@Override
							public void onPositiveClick(Dialog dialog, View view) {
//								upload2share(age);
							}
							
							@Override
							public void onNegativeClick(Dialog dialog, View view) {
								
							}
						}, MyDialog.ButtonConfirm);
				dialog2.show();
				break;
			case 9://定位成功，正在计算考勤
				if(dialog!=null)
					dialog.dismiss();
				dialog = null;
				if(dialog2!=null)
					dialog2.dismiss();
				dialog2 = null;
				dialog = DialogUtil.getNewWaitDialog("定位成功,正在计算考勤...",AttendanceActivity2.this);
				dialog.show();//分享中
				startCreate(mGpsAddr,mLongitude+"",mLatitude+"",mtype,
			    		time1,
			    		time2,
			    		attendancesectionid,
			    		procinsid);
				break;
			case 10://考勤结果
				if(dialog!=null)
				dialog.dismiss();
				dialog = null;
				if(dialog2!=null)
					dialog2.dismiss();
				dialog2 =null;		//remarkcode   errorMsg[errorType]
				dialog2 = DialogUtil.getMyDialog("考勤结果",
						(String)hm_remarkcode.get(remarkcode),
								AttendanceActivity2.this, new MyDialogListener() {
									
									@Override
									public void onPositiveClick(Dialog dialog, View view) {//考勤成功后更新考勤列表
//										upload2share(age);
								    	Date dNow = new Date();   //当前时间
								    	Date dBefore = new Date();
								    	Calendar calendar = Calendar.getInstance(); //得到日历
								    	calendar.setTime(dNow);//把当前时间赋给日历
								    	calendar.add(calendar.MONTH, -3);  //设置为前3月
								    	dBefore = calendar.getTime();   //得到前3月的时间

								    	SimpleDateFormat sdf=new SimpleDateFormat("yyyy-MM-dd"); //设置时间格式
								    	String defaultStartDate = sdf.format(dBefore);    //格式化前3月的时间
								    	String defaultEndDate = sdf.format(dNow); //格式化当前时间

								    	System.out.println("前3个月的时间是：" + defaultStartDate);
								    	System.out.println("生成的时间是：" + defaultEndDate);
								    	
								    	getAttendanceList(0,defaultStartDate,defaultEndDate);
									}
									
									@Override
									public void onNegativeClick(Dialog dialog, View view) {
										
									}
								}, MyDialog.ButtonConfirm);
				dialog2.show();
				break;
			default:
				if(errorType!=5)
					showCustomToast(errorMsg[errorType]);
				break;
			}
		}

	};
	String CurrentUid = "";
	String procinsid = "";
	private LinkedList linkedList = new LinkedList();//HashMap
	private String startdate1;//本考勤规则起始日期
    private String enddate1;//本考勤规则结束日期
    private String isweekend;//(休息日是否上班：周六班0，周日班1，周六日都班2，周末休息3),
    private String alternaterule;//（轮换规则：按天0，按周1，按半月2，按月3，按季度4，按半年5，按年轮换6，不轮换7）
    private String attendanceruleid;//考勤规则id
    private String attendanceshiftid;//考勤班次id （一天之内考勤的班段组合）
    private ArrayList aClassSections;
    private boolean initGetAttendance(String begindate,String enddate){//查询考勤记录
		try{
			if(BeemConnectivity.isConnected(getApplicationContext())){
		    if(mXmppFacade!=null 
					&& mXmppFacade.getXmppConnectionAdapter()!=null 
					&& mXmppFacade.getXmppConnectionAdapter().getAdaptee()!=null//&& !mXmppFacade.getXmppConnectionAdapter().getAdaptee().isAuthenticated()
					&& mXmppFacade.getXmppConnectionAdapter().getAdaptee().isConnected()
					&& mXmppFacade.getXmppConnectionAdapter().getAdaptee().isAuthenticated()
					&& mXmppFacade.getXmppConnectionAdapter().getAdaptee().isAlive()
					){
		    	AttendanceSearchIQ reqXML = new AttendanceSearchIQ();
	            reqXML.setId("1234567890");
	            reqXML.setApikey("abcdefghijklmnopqrstuvwxyz");
	            CurrentUid = StringUtils.parseBareAddress2(mXmppFacade.getXmppConnectionAdapter().getJID());
	            reqXML.setUid(StringUtils.parseBareAddress2(mXmppFacade.getXmppConnectionAdapter().getJID()));//2
	            SharedPreferences settings = PreferenceManager.getDefaultSharedPreferences(this);
	    	    String username = settings.getString(BeemApplication.ACCOUNT_USERNAME_KEY, "");
	          
	            reqXML.setBegindate(begindate);
	            reqXML.setEnddate(enddate);
	            String uuid = mXmppFacade.getXmppConnectionAdapter().getAdaptee().getUUID(this,username);
	            reqXML.setUuid(uuid);
//	            String hashcode = "";//apikey+view+orderby+uuid 使用登录成功后返回的sessionid作为密码做3des运算
	            String hash_dest_src = "abcdefghijklmnopqrstuvwxyz"+ StringUtils.parseBareAddress2(mXmppFacade.getXmppConnectionAdapter().getJID())+uuid;
	            String hash_dest = EncryptionUtil.getHash2(hash_dest_src, "SHA");
	            reqXML.setHashcode(hash_dest);
	            reqXML.setType(IQ.Type.SET);
	            String elementName = "attendancesearchiq"; 
	    		String namespace = "com:isharemessage:attendancesearchiq";
	    		AttendanceSearchIQResponseProvider provider = new AttendanceSearchIQResponseProvider();
	            Packet rt =  mXmppFacade.getXmppConnectionAdapter().excute(reqXML, "attendancesearchiq", "com:isharemessage:attendancesearchiq", provider);
	            
	            if(rt!=null){
	                if (rt instanceof AttendanceSearchIQResponse) {
	                	final AttendanceSearchIQResponse attendanceSearchIQResponse = (AttendanceSearchIQResponse) rt;

	                    if (attendanceSearchIQResponse.getChildElementXML().contains(
	                            "com:isharemessage:attendancesearchiq")) {
//	    					MainActivity.this.runOnUiThread(new Runnable() {
//		                    	
//    							@Override
//    							public void run() {
//    								showCustomToast("服务器应答消息："+contactGroupListIQResponse.toXML().toString());
//    							}
//    						});
	                        String Id = attendanceSearchIQResponse.getId();
	                        String Apikey = attendanceSearchIQResponse.getApikey();
	                        String retcode = attendanceSearchIQResponse.getRetcode();
	                        String memo = attendanceSearchIQResponse.getMemo();
	                        ArrayList aRecords = attendanceSearchIQResponse.getARecords();
	                        aClassSections = attendanceSearchIQResponse.getAClassSections();
	                        if(aClassSections.size()!=0){
	                        	Log.e("###########AttendanceClassSection响应packet结果解析###########", "Id="+((AttendanceClassSection)aClassSections.get(0)).getOnoffdutyname()); 
	                        }
	                        startdate1 = attendanceSearchIQResponse.getStartdate();
	                        enddate1 = attendanceSearchIQResponse.getEnddate();
	                        isweekend = attendanceSearchIQResponse.getIsweekend();
	                        alternaterule = attendanceSearchIQResponse.getAlternaterule();
	                        attendanceruleid = attendanceSearchIQResponse.getAttendanceruleid();
	                        attendanceshiftid = attendanceSearchIQResponse.getAttendanceshiftid();
	                        if(aRecords.size()!=0){
	                        	linkedList = new LinkedList(aRecords);
		                        Log.e("响应packet结果解析...............", "Id="+Id+";Apikey="+Apikey); 
		                        aRecords = null;
		                        return true;
	                        }
	                    }
	                } 
	            }
	            if(linkedList!=null && linkedList.size()!=0)
	    	    	errorType = 12;//查询成功
	    	    else{
	    	    	if(linkedList!=null && linkedList.size()==0)
	    	    		errorType = 13;
	    	    	else
	    	    		errorType = 14;
	    	    }
				mBinded = true;//20130804 added by allen
		    }else
		    	errorType = 1;
		    
			}else
				errorType = 4;
		}catch(RemoteException e){
			e.printStackTrace();
			errorType = 2;
		}catch(Exception e){
			e.printStackTrace();
			errorType = 3;
		}
		return false;
    }
	
    
	private boolean flag = false;
	private boolean isWork = false;
	private void getAttendanceList(final int type,final String defaultStartDate,final String defaultEndDate) {
//		private View view2;
//		private int type2;
		if(!isWork){
		putAsyncTask(new AsyncTask<Void, Void, Boolean>() {

			@Override
			protected void onPreExecute() {
				super.onPreExecute();
//				showLoadingDialog("正在加载,请稍后...");
//				showLoadingDialog();
//				if(type==0){
//					showLoadingDialog();
//				}
				if(flag || (type==0)){
//					showLoadingDialog("正在加载,请稍后...");
					xListViewHeader.setShowText("正在加载,请稍候...");
					xListViewHeader.setVisibility(View.VISIBLE);
					xListViewHeader.setState(2);
				} else if(type!=0){
					xListViewHeader.setState(0);
					xListViewHeader.setVisibility(View.GONE);
				}
			}

			@Override
			protected Boolean doInBackground(Void... params) {
				return initGetAttendance(defaultStartDate,defaultEndDate);
//				return true;
			}

			@Override
			protected void onPostExecute(Boolean result) {
				super.onPostExecute(result);
//				dismissLoadingDialog();
//				if(type==0){
////					   view.findViewById(R.id.pb).setVisibility(View.GONE);
//					dismissLoadingDialog();
//				}
//				if(flag || (type==0)){
//					xListViewHeader.setState(0);
//					xListViewHeader.setVisibility(View.GONE);
//				}
//				if (!result) {
//					showCustomToast("数据加载失败...");
//					mHandler2.sendEmptyMessage(3);
//				} else {
//					mHandler2.sendEmptyMessage(0);
//				}
				if (result) {	
//					parserJsonData(result,type,view);
//					initRefreshView(linkedList);
					parserData(type);
//					getData(2);
//					Message load = mHandler.obtainMessage(LOAD_DATA_FINISH, linkedList);
//					mHandler.sendMessage(load);
					
//					Message refresh = mHandler.obtainMessage(REFRESH_DATA_FINISH,
//							tempList);
//					mHandler.sendMessage(refresh);
				}else{
					//提示没有获取到数据：可能网络问题
					mHandler2.sendEmptyMessage(0);
				}
//				if(type==0){
//				   view.findViewById(R.id.pb).setVisibility(View.GONE);
//				}
				if(flag || (type==0)){
					xListViewHeader.setState(0);
					xListViewHeader.setVisibility(View.GONE);
				}
				flag = false;
				isWork = false;
			}

		});
		isWork = true;
		}
	}
    
	
	Uri uri = null;
	//利用requestCode区别开不同的返回结果
	//resultCode参数对应于子模块中setResut(int resultCode, Intent intent)函数中的resultCode值，用于区别不同的返回结果（如请求正常、请求异常等）
	//对应流程：
	//母模块startActivityForResult--触发子模块，根据不同执行结果设定resucode值，最后执行setResut并返回到木模块--母模块触发onActivityResult，根据requestcode参数区分不同子模块。
//    @Override
//    protected void onActivityResult(int requestCode, int resultCode, Intent data) {
//        super.onActivityResult(requestCode, resultCode, data);
//        if(requestCode==2 && resultCode==2 && data!=null){
//        	String filepath = data.getStringExtra("filepath");
//        	Toast.makeText(AttendanceActivity2.this, "filepath="+filepath, Toast.LENGTH_LONG).show();
//			if(filepath.length() > 0){
////				sendFile(filepath);//P2P send file
//				File file = new File(filepath);
//				if (file.exists() && file.canRead()) {
//					sendOfflineFile(filepath,"file");//send offline file via agent file server 
//								    
//				} else {
//					Toast.makeText(AttendanceActivity2.this, "file not exists", Toast.LENGTH_LONG).show();
//				}
//			}
//        }
//        else if ( requestCode == GalleryHelper.GALLERY_REQUEST_CODE) {
//            if ( resultCode == GalleryHelper.GALLERY_RESULT_SUCCESS ) {
//                PhotoInfo photoInfo = data.getParcelableExtra(GalleryHelper.RESULT_DATA);
//                List<PhotoInfo> photoInfoList = (List<PhotoInfo>) data.getSerializableExtra(GalleryHelper.RESULT_LIST_DATA);
//
//                if ( photoInfo != null ) {
////                    ImageLoader.getInstance().displayImage("file:/" + photoInfo.getPhotoPath(), mIvResult);
//                    uri = Uri.parse("file:/" + photoInfo.getPhotoPath());
//                    Toast.makeText(this, "选择了照片路径:" + photoInfo.getPhotoPath(), Toast.LENGTH_SHORT).show();
//                    sendOfflineFile(photoInfo.getPhotoPath(),"img");
//                }
//
//                if ( photoInfoList != null ) {
//                    Toast.makeText(this, "选择了" + photoInfoList.size() + "张", Toast.LENGTH_SHORT).show();
//                }
//            }
//        }
//        else if ( requestCode == GalleryHelper.TAKE_REQUEST_CODE ) {
//            if (resultCode == RESULT_OK && mTakePhotoUri != null) {
//                final String path = mTakePhotoUri.getPath();
//                final PhotoInfo info = new PhotoInfo();
//                info.setPhotoPath(path);
////                updateGallery(path);
//
//                final int degress = BitmapUtils.getDegress(path);
//                if (degress != 0) {
//                    new AsyncTask<Void, Void, Void>() {
//
//                        @Override
//                        protected void onPreExecute() {
//                            super.onPreExecute();
//                            toast("请稍等…");
//                        }
//
//                        @Override
//                        protected Void doInBackground(Void... params) {
//                            try {
//                                Bitmap bitmap = rotateBitmap(path, degress);
//                                saveRotateBitmap(bitmap, path);
//                                bitmap.recycle();
//                            } catch (Exception e) {
//                                Logger.e(e);
//                            }
//                            return null;
//                        }
//
//                        @Override
//                        protected void onPostExecute(Void voids) {
//                            super.onPostExecute(voids);
////                            takeResult(info);
//                            toPhotoCrop(info);
//                        }
//                    }.execute();
//                } else {
////                    takeResult(info);
//                	toPhotoCrop(info);
//                }
//            } else {
//                toast("拍照失败");
//            }
//        } else if ( requestCode == GalleryHelper.CROP_REQUEST_CODE) {
//            if ( resultCode == GalleryHelper.CROP_SUCCESS ) {
//                PhotoInfo photoInfo = data.getParcelableExtra(GalleryHelper.RESULT_DATA);
//                resultSingle(photoInfo);
//            }
//        } else if ( requestCode == GalleryHelper.GALLERY_RESULT_SUCCESS ) {
//            PhotoInfo photoInfo = data.getParcelableExtra(GalleryHelper.RESULT_DATA);
//            List<PhotoInfo> photoInfoList = (List<PhotoInfo>) data.getSerializableExtra(GalleryHelper.RESULT_LIST_DATA);
//
//            if ( photoInfo != null ) {
////                ImageLoader.getInstance().displayImage("file:/" + photoInfo.getPhotoPath(), mIvResult);
//                uri = Uri.parse("file:/" + photoInfo.getPhotoPath());
//                Toast.makeText(this, "选择了照片路径:" + photoInfo.getPhotoPath(), Toast.LENGTH_SHORT).show();
//                sendOfflineFile(photoInfo.getPhotoPath(),"img");
//            }
//
//            if ( photoInfoList != null ) {
//                Toast.makeText(this, "选择了" + photoInfoList.size() + "张", Toast.LENGTH_SHORT).show();
//            }
//        }
//    }
    
    //recodeTime
    String transformfilepath = "";
    String transformfiletype = "";
    private void sendOfflineFile(String filepath,String type) {
		
    	transformfilepath = filepath;
    	transformfiletype = type;
    	
		try{
    		File file2 = new File(transformfilepath);
    		if(file2.exists()){
    			Bitmap bitmap = BitmapFactory.decodeFile(transformfilepath);
//    			setUserPhoto(bitmap);
    			upload(transformfilepath,"9999");
    			
    		}
		}catch(Exception e){
			e.printStackTrace();
		}
		
	}
    
    
    /**
     * 拍照
     */
    String mPhotoTargetFolder = null;
    Uri mTakePhotoUri = null;
    protected void takePhotoAction() {

        if (!DeviceUtils.existSDCard()) {
//            toast("没有SD卡不能拍照呢~");
        	Toast.makeText(this, "没有SD卡不能拍照呢~", Toast.LENGTH_SHORT).show();
            return;
        }

        File takePhotoFolder = null;
        if (cn.finalteam.toolsfinal.StringUtils.isEmpty(mPhotoTargetFolder)) {
            takePhotoFolder = new File(Environment.getExternalStorageDirectory(),
                    "/DCIM/" + GalleryHelper.TAKE_PHOTO_FOLDER);
        } else {
            takePhotoFolder = new File(mPhotoTargetFolder);
        }

        File toFile = new File(takePhotoFolder, "IMG" + DateUtils.format(new Date(), "yyyyMMddHHmmss") + ".jpg");
        boolean suc = FileUtils.makeFolders(toFile);
        Logger.d("create folder=" + toFile.getAbsolutePath());
        if (suc) {
            mTakePhotoUri = Uri.fromFile(toFile);
            Intent captureIntent = new Intent(MediaStore.ACTION_IMAGE_CAPTURE);
            captureIntent.putExtra(MediaStore.EXTRA_OUTPUT, mTakePhotoUri);
            startActivityForResult(captureIntent, GalleryHelper.TAKE_REQUEST_CODE);
        }
    }
    protected int mScreenWidth = 720;
    protected int mScreenHeight = 1280;
    protected Bitmap rotateBitmap(String path, int degress) {
        try {
            Bitmap bitmap = BitmapUtils.compressBitmap(path, mScreenWidth / 4, mScreenHeight / 4);
            bitmap = BitmapUtils.rotateBitmap(bitmap, degress);
            return bitmap;
        } catch (Exception e) {
            Logger.e(e);
        }

        return null;
    }

    protected void saveRotateBitmap(Bitmap bitmap, String path) {
        //保存
        BitmapUtils.saveBitmap(bitmap, new File(path));
        //修改数据库
        ContentValues cv = new ContentValues();
        cv.put("orientation", 0);
        ContentResolver cr = getContentResolver();
        String where = new String(MediaStore.Images.Media.DATA + "='" + cn.finalteam.toolsfinal.StringUtils.sqliteEscape(path) +"'");
        cr.update(MediaStore.Images.Media.EXTERNAL_CONTENT_URI, cv, where, null);
    }
    public void toast(String msg) {
        Toast.makeText(this, msg, Toast.LENGTH_SHORT).show();
    }
    protected void resultSingle(PhotoInfo photoInfo) {
//        Intent intent = getIntent();
//        if (intent == null) {
//            intent = new Intent();
//        }
//        intent.putExtra(GalleryHelper.RESULT_DATA, photoInfo);
////        setResult(GalleryHelper.GALLERY_RESULT_SUCCESS, intent);
////        finish();
//        startActivityForResult(intent, GalleryHelper.GALLERY_RESULT_SUCCESS);
    	
        if ( photoInfo != null ) {
//          ImageLoader.getInstance().displayImage("file:/" + photoInfo.getPhotoPath(), mIvResult);
          uri = Uri.parse("file:/" + photoInfo.getPhotoPath());
          Toast.makeText(this, "选择了照片路径:" + photoInfo.getPhotoPath(), Toast.LENGTH_SHORT).show();
          sendOfflineFile(photoInfo.getPhotoPath(),"img");
      }
    }
    /**
     * 执行裁剪
     */
    protected void toPhotoCrop(PhotoInfo info) {
        Intent intent = new Intent(this, PhotoCropActivity.class);
        intent.putExtra(PhotoCropActivity.PHOTO_INFO, info);
        startActivityForResult(intent, GalleryHelper.CROP_REQUEST_CODE);
    }
    
    
    public void upload(String mPicPath,String fromAccount){
    	try{
            final File file = new File(mPicPath);  
            
            if (file != null) {  
//                String request = UploadUtil.uploadFile(file, requestURL);  
//                String uploadHost="http://10.0.2.2:9090/plugins/offlinefiletransfer/offlinefiletransfer";  
            	String uploadHost = XmppConnectionAdapter.uploadHost.replace("OfflinefiletransferServlet", "UploadHeadServlet");
//                RequestParams params=new RequestParams();  
////                params.addBodyParameter("msg",imgtxt.getText().toString());   
//                params.addBodyParameter(picPath.replace("/", ""), file);   
//                uploadMethod(params,uploadHost);
////                uploadImage.setText(request);  
                RequestParams params = new RequestParams();
//                params.addHeader("name", "value");
//                params.addHeader(HttpUtils.HEADER_ACCEPT_ENCODING, HttpUtils.ENCODING_GZIP);
                params.addHeader("Accept-Encoding", "gzip");
//                params.addQueryStringParameter("name", "value");
                params.addQueryStringParameter("fromAccount", fromAccount);//代表存储目录
                params.addQueryStringParameter("sendType", "img");
                params.addQueryStringParameter("sendSize", "0");
                // 只包含字符串参数时默认使用BodyParamsEntity，
                // 类似于UrlEncodedFormEntity（"application/x-www-form-urlencoded"）。
//                params.addBodyParameter("fromAccount", fromAccount);
//                params.addBodyParameter("toAccount", toAccount);
//                params.addBodyParameter("sendType", "audio");
//                params.addBodyParameter("sendSize", (int) mRecord_Time+"");

                // 加入文件参数后默认使用MultipartEntity（"multipart/form-data"），
                // 如需"multipart/related"，xUtils中提供的MultipartEntity支持设置subType为"related"。
                // 使用params.setBodyEntity(httpEntity)可设置更多类型的HttpEntity（如：
                // MultipartEntity,BodyParamsEntity,FileUploadEntity,InputStreamUploadEntity,StringEntity）。
                // 例如发送json参数：params.setBodyEntity(new StringEntity(jsonStr,charset));
//                BodyParamsEntity bpe = new BodyParamsEntity();
//                bpe.addParameter("fromAccount", fromAccount);
//                bpe.addParameter("toAccount", toAccount);
//                bpe.addParameter("sendType", "audio");
//                bpe.addParameter("sendSize", (int) mRecord_Time+"");
//                params.setBodyEntity(bpe);
                params.addBodyParameter("file", file);
                uploadMethod(params,uploadHost);
                
            }  
    	}catch(Exception e){
    		e.printStackTrace();
    	}
    }
    
	private HttpUtils http;
	private HttpHandler handler;
	
    //上传照片start
    public  void uploadMethod(final RequestParams params,final String uploadHost) {  
    	http = new HttpUtils();
    	http.configCurrentHttpCacheExpiry(1000 * 10); // 设置缓存10秒，10秒内直接返回上次成功请求的结果。
    	
    	handler = http.send(HttpRequest.HttpMethod.POST, uploadHost, params,new RequestCallBack<String>() {  
                    @Override  
                    public void onStart() {  
//                      msgTextview.setText("conn...");  
                      mHandler.sendEmptyMessage(4);
                    }  
                    @Override  
                    public void onLoading(long total, long current,boolean isUploading) {  
//                        if (isUploading) {  
//                          msgTextview.setText("upload: " + current + "/"+ total);  
//                        } else {  
//                          msgTextview.setText("reply: " + current + "/"+ total);  
//                        }  
    					android.os.Message message = mHandler.obtainMessage();
//    					message.arg1 = (int) (current*100/total);
    					message.arg1 = 80;//gzip 后 total为0
    					message.what = 1;
    		//								message.sendToTarget();
    					mHandler.sendMessage(message);
                    }  
                    public void onSuccess(ResponseInfo<String> responseInfo) { 
                    	Log.e("※※※※※####20140806####※※※※※", "※※上传成功"+responseInfo.statusCode+";reply: " + responseInfo.result);
                    	//statuscode == 200
//                      msgTextview.setText("statuscode:"+responseInfo.statusCode+";reply: " + responseInfo.result); 
                    	
                    	mHandler.sendEmptyMessage(2);
                    }  
                    public void onFailure(HttpException error, String msg) {  
//                      msgTextview.setText(error.getExceptionCode() + ":" + msg);  
                    	Log.e("※※※※※####20140806####※※※※※", "※※上传失败"+error.getExceptionCode() + ":" + msg);
                    	mHandler.sendEmptyMessage(3);
                    }  
                });  
        
    } 
    //上传照片end
    
    private  Dialog creatingProgress = null;
	private ProgressBar bar;
	private TextView progress;
	private TextView progressMainText;
	
	public void initialProgressDialog(){
		//创建处理进度条
		creatingProgress= new Dialog(AttendanceActivity2.this,R.style.Dialog_loading_noDim);
		Window dialogWindow = creatingProgress.getWindow();
		WindowManager.LayoutParams lp = dialogWindow.getAttributes();
		lp.width = (int) (getResources().getDisplayMetrics().density*240);
		lp.height = (int) (getResources().getDisplayMetrics().density*80);
		lp.gravity = Gravity.CENTER;
		dialogWindow.setAttributes(lp);
		creatingProgress.setCanceledOnTouchOutside(false);//禁用取消按钮
		creatingProgress.setContentView(R.layout.activity_recorder_progress);
		
		progress = (TextView) creatingProgress.findViewById(R.id.recorder_progress_progresstext);
		progressMainText = (TextView)creatingProgress.findViewById(R.id.recorder_progress_maintext);
		bar = (ProgressBar) creatingProgress.findViewById(R.id.recorder_progress_progressbar);
	}
	
	
	public void locate() {
		if(BeemConnectivity.isConnected(getApplicationContext())){
		BaiduMapUtilByRacer.locateByBaiduMap(mContext, 2000,
				new LocateListener() {

					@Override
					public void onLocateSucceed(LocationBean locationBean) {
						mLocationBean = locationBean;
						
						mLongitude = locationBean.getLongitude();
						mLatitude = locationBean.getLatitude();
						mGpsAddr = locationBean.getLocName();
						
////						mHandler.sendEmptyMessage(2);
//						android.os.Message message = mHandler.obtainMessage();
////    					message.arg1 = (int) (current*100/total);
//    					message.arg1 = 80;//gzip 后 total为0
//    					message.what = 1;
//    		//								message.sendToTarget();
//    					mHandler.sendMessage(message);
////						mBackDialog.getProgress().setProgress(100);
//						mHandler.sendEmptyMessage(5);//定位成功
						mHandler.sendEmptyMessage(9);//定位成功，正在计算考勤
					}

					@Override
					public void onLocateFiled() {
//						mHandler.sendEmptyMessage(3);
//////						mBackDialog.getProgress().setProgress(0);
						mHandler.sendEmptyMessage(6);
					}

					@Override
					public void onLocating() {
//						mHandler.sendEmptyMessage(4);
//////						mBackDialog.getProgress().setProgress(50);
						mHandler.sendEmptyMessage(7);
					}
				});
		}else{
			mHandler.sendEmptyMessage(8);//网络连接不可用,请检查你的网络设置.
		}
	}
	
	
	private BaseDialog mBackDialog;
	private void initDialog() {
		mBackDialog = BaseDialog.getDialog(AttendanceActivity2.this, "提示",
				"定为考勤进行中?", true,"确认", new DialogInterface.OnClickListener() {

					@Override
					public void onClick(DialogInterface dialog, int which) {
						dialog.dismiss();
						finish();
					}
				}, "取消", new DialogInterface.OnClickListener() {

					@Override
					public void onClick(DialogInterface dialog, int which) {
						dialog.cancel();
					}
				});
		mBackDialog.setButton1Background(R.drawable.btn_default_popsubmit);

	}
	
	
	private void initPopupWindow() {
		mPopupWindow = new NearByPopupWindow2(this,this);
		mPopupWindow.setOnSubmitClickListener(new onSubmitClickListener() {

			@Override
			public void onClick() {
//				mPeopleFragment.onManualRefresh();
			}
		});
		mPopupWindow.setOnDismissListener(new OnDismissListener() {

			@Override
			public void onDismiss() {
//				mHeaderSpinner.initSpinnerState(false);
			}
		});
		mPopupWindow.registerGpsFilterCallback(AttendanceActivity2.this);
	}
	
	//0全部 1男 2女
	private int mGenderSelect = 0;
    //不限(0),16–22岁(1),23–30岁(2),31岁以上(3)</item>
	private int mAgeSelect = 0;
	//0 不限,1 15分钟,2 60分钟,3 3天
	private int mTimeSelect = 0;
	@Override
	public void gpsFilterChanged(int GenderSelect,int AgeSelect,int TimeSelect) {
		mGenderSelect = GenderSelect;
		mAgeSelect = AgeSelect;
		mTimeSelect = TimeSelect;
//		mHandler2.sendEmptyMessage(10);
		if(dialog!=null)
			dialog.dismiss();
		dialog = null;
		if(dialog2!=null)
			dialog2.dismiss();
		dialog2 = null;
		dialog = DialogUtil.getNewWaitDialog("正在定位考勤...",AttendanceActivity2.this);
		dialog.show();//分享中
		locate();
	}
	
	//弹出对话框下拉列表选择值
	String mtype;
	String time1;
	String time2;
	String attendancesectionid;
	
	
	
	
	
	/**
	 * ListView数据适配器
	 * @author Administrator
	 *  
	 */
	public class CustomListAdapter extends BaseAdapter implements RecyclerListener{

		private LayoutInflater mInflater;
		public LinkedList<AttendanceRecord2> mList;
		
	    private LinkedList<AttendanceRecord2> mOriginalValues;
	    private final Object mLock = new Object();

		public CustomListAdapter(Context pContext, LinkedList<AttendanceRecord2> pList) {
			mInflater = LayoutInflater.from(pContext);
			if(pList != null){
				mList = pList;
			}else{
				mList = new LinkedList<AttendanceRecord2>();
			}
		}
		
		@Override
		public int getCount() {
        	return mList.size();
		}

		@Override
		public Object getItem(int position) {
			return mList.get(position);
		}

		@Override
		public long getItemId(int position) {
			return position;
		}
		
        public void addItemLast(List<AttendanceRecord2> datas) {
        	Log.d("ContactFrameActivity", "CustomListAdapter addItemLast 1 ");
        	if(datas!=null){
        		mList.clear();
        		Log.d("ContactFrameActivity", "CustomListAdapter addItemLast 2 ");
            	for (AttendanceRecord2 info : datas) {
            		mList.add(info);
            		Log.d("ContactFrameActivity", "CustomListAdapter addItemLast 3 ");
                }
        	}
        }
        public void addItemLast_refresh_roster(List<AttendanceRecord2> datas) {
        	Log.d("ContactFrameActivity", "CustomListAdapter addItemLast 1 ");
        	if(datas!=null){
//        		mList.clear();
        		Log.d("ContactFrameActivity", "CustomListAdapter addItemLast 2 ");
            	for (AttendanceRecord2 info : datas) {
            		mList.add(info);
            		Log.d("ContactFrameActivity", "CustomListAdapter addItemLast 3 ");
                }
        	}
        }
        public void delItemLast_refresh_roster(List<AttendanceRecord2> datas) {
        	Log.d("ContactFrameActivity", "CustomListAdapter delItemLast_refresh_roster 1 ");
        	int idx = -1;
        	if(datas!=null){
//        		mList.clear();
        		Log.d("ContactFrameActivity", "CustomListAdapter delItemLast_refresh_roster 2 ");
            	for (AttendanceRecord2 info : datas) {
            		idx = containsKey(info.getId_gc());
            		if(idx!=-1)
//            			mList.remove(info);
            			mList.remove(idx);
            		Log.d("ContactFrameActivity", "CustomListAdapter delItemLast_refresh_roster 3 ");
                }
        	}
        }
        public void updateItemLast_refresh_roster(List<AttendanceRecord2> datas) {
        	Log.d("ContactFrameActivity", "CustomListAdapter updateItemLast_refresh_roster 1 ");
        	int idx = -1;
        	if(datas!=null){
//        		mList.clear();
        		Log.d("ContactFrameActivity", "CustomListAdapter updateItemLast_refresh_roster 2 ");
            	for (AttendanceRecord2 info : datas) {
            		idx = containsKey(info.getId_gc());
            		if(idx!=-1){
//            			mList.remove(info);
            			mList.remove(idx);
            			mList.add(info);
            		}
            		Log.d("ContactFrameActivity", "CustomListAdapter updateItemLast_refresh_roster 3 ");
                }
        	}
        }
        
        public int containsKey(String key){
        	int i = 0;
        		Iterator<AttendanceRecord2> it = mList.iterator();
        		AttendanceRecord2 di;
        		while(it.hasNext()){
        			di = it.next();
        			
        		    if(di.getId_gc().equals(key))
//        			if(di.getJID().equals(key))
        		    	return i;
        		    i++;
        		}
        	return -1;
        }

		@Override
		public View getView(int position, View convertView, ViewGroup parent) {
			if (getCount() == 0) {
				return null;
			}
			ViewHolder holder = null;
			if (convertView == null) {
				convertView = mInflater.inflate(R.layout.listitem_attendances, null);

				holder = new ViewHolder();
				holder.item_htv_year = (HandyTextView)convertView.findViewById(R.id.item_htv_year);
				holder.item_htv_monthday = (HandyTextView)convertView.findViewById(R.id.item_htv_monthday);
				
                holder.item_layout_classsection11 = (LinearLayout)convertView.findViewById(R.id.item_layout_classsection11);
                holder.attendance_item_layout_classsection_name11 = (HandyTextView)convertView.findViewById(R.id.attendance_item_layout_classsection_name11);
                holder.attendance_item_layout_classsection_record111 = (LinearLayout)convertView.findViewById(R.id.attendance_item_layout_classsection_record111);
                holder.attendance_item_layout_classsection_time11 = (HandyTextView)convertView.findViewById(R.id.attendance_item_layout_classsection_time11);
                holder.attendance_item_layout_classsection_status11 = (HandyTextView)convertView.findViewById(R.id.attendance_item_layout_classsection_status11);
                holder.attendance_item_layout_classsection_img_in11 = (ImageView)convertView.findViewById(R.id.attendance_item_layout_classsection_img_in11);
                holder.attendance_item_layout_classsection_record121 = (LinearLayout)convertView.findViewById(R.id.attendance_item_layout_classsection_record121);
                holder.attendance_item_layout_classsection_time12 = (HandyTextView)convertView.findViewById(R.id.attendance_item_layout_classsection_time12);
                holder.attendance_item_layout_classsection_status12 = (HandyTextView)convertView.findViewById(R.id.attendance_item_layout_classsection_status12);
                holder.attendance_item_layout_classsection_img_in12 = (ImageView)convertView.findViewById(R.id.attendance_item_layout_classsection_img_in12);
                
                holder.item_layout_classsection22 = (LinearLayout)convertView.findViewById(R.id.item_layout_classsection22);
                holder.attendance_item_layout_classsection_name22 = (HandyTextView)convertView.findViewById(R.id.attendance_item_layout_classsection_name22);
                holder.attendance_item_layout_classsection_record211 = (LinearLayout)convertView.findViewById(R.id.attendance_item_layout_classsection_record211);
                holder.attendance_item_layout_classsection_time21 = (HandyTextView)convertView.findViewById(R.id.attendance_item_layout_classsection_time21);
                holder.attendance_item_layout_classsection_status21 = (HandyTextView)convertView.findViewById(R.id.attendance_item_layout_classsection_status21);
                holder.attendance_item_layout_classsection_img_in21 = (ImageView)convertView.findViewById(R.id.attendance_item_layout_classsection_img_in21);
                holder.attendance_item_layout_classsection_record221 = (LinearLayout)convertView.findViewById(R.id.attendance_item_layout_classsection_record221);
                holder.attendance_item_layout_classsection_time22 = (HandyTextView)convertView.findViewById(R.id.attendance_item_layout_classsection_time22);
                holder.attendance_item_layout_classsection_status22 = (HandyTextView)convertView.findViewById(R.id.attendance_item_layout_classsection_status22);
                holder.attendance_item_layout_classsection_img_in22 = (ImageView)convertView.findViewById(R.id.attendance_item_layout_classsection_img_in22);
                
                holder.item_layout_classsection33 = (LinearLayout)convertView.findViewById(R.id.item_layout_classsection33);
                holder.attendance_item_layout_classsection_name33 = (HandyTextView)convertView.findViewById(R.id.attendance_item_layout_classsection_name33);
                holder.attendance_item_layout_classsection_record311 = (LinearLayout)convertView.findViewById(R.id.attendance_item_layout_classsection_record311);
                holder.attendance_item_layout_classsection_time31 = (HandyTextView)convertView.findViewById(R.id.attendance_item_layout_classsection_time31);
                holder.attendance_item_layout_classsection_status31 = (HandyTextView)convertView.findViewById(R.id.attendance_item_layout_classsection_status31);
                holder.attendance_item_layout_classsection_img_in31 = (ImageView)convertView.findViewById(R.id.attendance_item_layout_classsection_img_in31);
                holder.attendance_item_layout_classsection_record321 = (LinearLayout)convertView.findViewById(R.id.attendance_item_layout_classsection_record321);
                holder.attendance_item_layout_classsection_time32 = (HandyTextView)convertView.findViewById(R.id.attendance_item_layout_classsection_time32);
                holder.attendance_item_layout_classsection_status32 = (HandyTextView)convertView.findViewById(R.id.attendance_item_layout_classsection_status32);
                holder.attendance_item_layout_classsection_img_in32 = (ImageView)convertView.findViewById(R.id.attendance_item_layout_classsection_img_in32);
                
                holder.item_layout_classsection44 = (LinearLayout)convertView.findViewById(R.id.item_layout_classsection44);
                holder.attendance_item_layout_classsection_name44 = (HandyTextView)convertView.findViewById(R.id.attendance_item_layout_classsection_name44);
                holder.attendance_item_layout_classsection_record411 = (LinearLayout)convertView.findViewById(R.id.attendance_item_layout_classsection_record411);
                holder.attendance_item_layout_classsection_time41 = (HandyTextView)convertView.findViewById(R.id.attendance_item_layout_classsection_time41);
                holder.attendance_item_layout_classsection_status41 = (HandyTextView)convertView.findViewById(R.id.attendance_item_layout_classsection_status41);
                holder.attendance_item_layout_classsection_img_in41 = (ImageView)convertView.findViewById(R.id.attendance_item_layout_classsection_img_in41);
                holder.attendance_item_layout_classsection_record421 = (LinearLayout)convertView.findViewById(R.id.attendance_item_layout_classsection_record421);
                holder.attendance_item_layout_classsection_time42 = (HandyTextView)convertView.findViewById(R.id.attendance_item_layout_classsection_time42);
                holder.attendance_item_layout_classsection_status42 = (HandyTextView)convertView.findViewById(R.id.attendance_item_layout_classsection_status42);
                holder.attendance_item_layout_classsection_img_in42 = (ImageView)convertView.findViewById(R.id.attendance_item_layout_classsection_img_in42);
                
                convertView.setTag(holder);
			} else {
				holder = (ViewHolder) convertView.getTag();
			}
			AttendanceRecord2 detail=mList.get(position);
            //查询结果为最近三个月
			holder.item_htv_year.setText(detail.getYearstr());
			holder.item_htv_monthday.setText(detail.getMonthdaystr());
			
			holder.item_layout_classsection11.setVisibility(View.GONE);
			holder.item_layout_classsection22.setVisibility(View.GONE);
			holder.item_layout_classsection33.setVisibility(View.GONE);
			holder.item_layout_classsection44.setVisibility(View.GONE);
			holder.attendance_item_layout_classsection_record111.setVisibility(View.GONE);
			holder.attendance_item_layout_classsection_record121.setVisibility(View.GONE);
			holder.attendance_item_layout_classsection_record211.setVisibility(View.GONE);
			holder.attendance_item_layout_classsection_record221.setVisibility(View.GONE);
			holder.attendance_item_layout_classsection_record311.setVisibility(View.GONE);
			holder.attendance_item_layout_classsection_record321.setVisibility(View.GONE);
			holder.attendance_item_layout_classsection_record411.setVisibility(View.GONE);
			holder.attendance_item_layout_classsection_record421.setVisibility(View.GONE);
			
			
			String s = detail.getMtype_gc();//0,1,0,1这种形式
			String arr_mtype[] = s.split(",");
			String s1 = detail.getMintime_gc();
			String arr_mintime[] = s1.split(",");
			String s2 = detail.getMaxtime_gc();
			String arr_maxtime[] = s2.split(",");
			String s3 = detail.getOnoffdutyname_gc();
			String arr_onoffdutyname[] = s3.split(",");
			String s4 = detail.getStarttime_gc();
			String arr_starttime[] = s4.split(",");
			String s5 = detail.getEndtime_gc();
			String arr_endtime[] = s5.split(",");
			String s6 = detail.getRemarks_gc();
			String arr_remarks_gc[] = s6.split(",");
			String s7 = detail.getRemarkcode_gc();
			String arr_remarkcode_gc[] = s7.split(",");
			String s8 = detail.getId_gc();
			String arr_id_gc[] = s8.split(",");
			String s9 = detail.getCreate_date_gc();
			String arr_create_date_gc[] = s9.split(",");
			String s10 = detail.getAttendancesectionid_gc();
			
			
			
			String s0 = detail.getAttendancesectionid_gc();
			String arr[] = s0.split(",");
			
			
			ArrayList<AttendanceRecord2> list = new ArrayList<AttendanceRecord2>();
			AttendanceRecord2 attendanceRecord2 = null;
			if(arr!=null
					&& arr.length!=0){
				for(int i=0;i<arr.length;i++){
					attendanceRecord2 = new AttendanceRecord2();
					attendanceRecord2.setYearstr(detail.getYearstr());
					attendanceRecord2.setMonthdaystr(detail.getMonthdaystr());
					attendanceRecord2.setUid(detail.getUid());
					attendanceRecord2.setId_gc(arr_id_gc[i]);
					attendanceRecord2.setCreate_date_gc(arr_create_date_gc[i]);
					attendanceRecord2.setRemarks_gc(arr_remarks_gc[i]);
					attendanceRecord2.setRemarkcode_gc(arr_remarkcode_gc[i]);
					attendanceRecord2.setAttendanceruleid(detail.getAttendanceruleid());
					attendanceRecord2.setAttendanceshiftid(detail.getAttendanceshiftid());
					attendanceRecord2.setAttendancesectionid_gc(arr[i]);
					attendanceRecord2.setMtype_gc(arr_mtype[i]);
					attendanceRecord2.setMintime_gc(arr_mintime[i]);
					attendanceRecord2.setMaxtime_gc(arr_maxtime[i]);
					attendanceRecord2.setOnoffdutyname_gc(arr_onoffdutyname[i]);
					attendanceRecord2.setStarttime_gc(arr_starttime[i]);
					attendanceRecord2.setEndtime_gc(arr_endtime[i]);
					list.add(attendanceRecord2);
				}
				
				Map<String, List<AttendanceRecord2>> map2 = buildDbEventsMap(list);
				
				Iterator iter = map2.entrySet().iterator();
				Map.Entry entry = null;
				Object val = null;
				Object key = null;
				List<AttendanceRecord2> list2 = null;
				AttendanceRecord2 ar2 = null;
				int p = 0;
				while (iter.hasNext()) {
					entry = (Map.Entry) iter.next();
					key = entry.getKey();
					val = entry.getValue();
					list2 = (List<AttendanceRecord2>)val;
//					System.out.println("key="+key);
					for(int m=0;m<list2.size();m++){
						ar2 = (AttendanceRecord2)list2.get(m);
//						System.out.println("ar2="+ar2.getOnoffdutyname_gc()+";"+ar2.getMtype_gc());
						if(p==0){
							holder.item_layout_classsection11.setVisibility(View.VISIBLE);
							holder.attendance_item_layout_classsection_name11.setText(ar2.getOnoffdutyname_gc()+" "+ar2.getStarttime_gc()+"-"+ar2.getEndtime_gc());
							if(ar2.getMtype_gc().equals("0")){
			                	holder.attendance_item_layout_classsection_record111.setVisibility(View.VISIBLE);
								holder.attendance_item_layout_classsection_time11.setText(ar2.getMintime_gc());
								holder.attendance_item_layout_classsection_img_in11.setImageResource(getRemarkImg(ar2.getRemarkcode_gc()));
				                holder.attendance_item_layout_classsection_status11.setText(ar2.getRemarkcode_gc());
				                
				                if(list2.size()==1){
				                	holder.attendance_item_layout_classsection_record121.setVisibility(View.VISIBLE);
					                holder.attendance_item_layout_classsection_time12.setText("下班没有打卡");
					                holder.attendance_item_layout_classsection_img_in12.setImageResource(R.drawable.attendance_weishuaka);
					                holder.attendance_item_layout_classsection_status12.setText("");
				                }
			                }else if(ar2.getMtype_gc().equals("1")){
			                	holder.attendance_item_layout_classsection_record121.setVisibility(View.VISIBLE);
				                holder.attendance_item_layout_classsection_time12.setText(ar2.getMaxtime_gc());
				                holder.attendance_item_layout_classsection_img_in12.setImageResource(getRemarkImg(ar2.getRemarkcode_gc()));
				                holder.attendance_item_layout_classsection_status12.setText(ar2.getRemarkcode_gc());
				                if(list2.size()==1){
				                	holder.attendance_item_layout_classsection_record111.setVisibility(View.VISIBLE);
									holder.attendance_item_layout_classsection_time11.setText("上班没有打卡");
									holder.attendance_item_layout_classsection_img_in11.setImageResource(R.drawable.attendance_weishuaka);
									holder.attendance_item_layout_classsection_status11.setText("");
				                }
			                }
						}
						else if(p==1){
							holder.item_layout_classsection22.setVisibility(View.VISIBLE);
							holder.attendance_item_layout_classsection_name22.setText(ar2.getOnoffdutyname_gc()+" "+ar2.getStarttime_gc()+"-"+ar2.getEndtime_gc());
							if(ar2.getMtype_gc().equals("0")){
			                	holder.attendance_item_layout_classsection_record211.setVisibility(View.VISIBLE);
								holder.attendance_item_layout_classsection_time21.setText(ar2.getMintime_gc());
								holder.attendance_item_layout_classsection_img_in21.setImageResource(getRemarkImg(ar2.getRemarkcode_gc()));
				                holder.attendance_item_layout_classsection_status21.setText(ar2.getRemarkcode_gc());
				                if(list2.size()==1){
				                	holder.attendance_item_layout_classsection_record221.setVisibility(View.VISIBLE);
					                holder.attendance_item_layout_classsection_time22.setText("下班没有打卡");
					                holder.attendance_item_layout_classsection_img_in22.setImageResource(R.drawable.attendance_weishuaka);
					                holder.attendance_item_layout_classsection_status22.setText("");
				                }
							}else if(ar2.getMtype_gc().equals("1")){
								holder.attendance_item_layout_classsection_record221.setVisibility(View.VISIBLE);
				                holder.attendance_item_layout_classsection_time22.setText(ar2.getMaxtime_gc());
				                holder.attendance_item_layout_classsection_img_in22.setImageResource(getRemarkImg(ar2.getRemarkcode_gc()));
				                holder.attendance_item_layout_classsection_status22.setText(ar2.getRemarkcode_gc());
				                if(list2.size()==1){
				                	holder.attendance_item_layout_classsection_record211.setVisibility(View.VISIBLE);
									holder.attendance_item_layout_classsection_time21.setText("上班没有打卡");
									holder.attendance_item_layout_classsection_img_in21.setImageResource(R.drawable.attendance_weishuaka);
					                holder.attendance_item_layout_classsection_status21.setText("");
				                }
							}
						}
						else if(p==2){
							holder.item_layout_classsection33.setVisibility(View.VISIBLE);
							holder.attendance_item_layout_classsection_name33.setText(ar2.getOnoffdutyname_gc()+" "+ar2.getStarttime_gc()+"-"+ar2.getEndtime_gc());
							if(ar2.getMtype_gc().equals("0")){
			                	holder.attendance_item_layout_classsection_record311.setVisibility(View.VISIBLE);
								holder.attendance_item_layout_classsection_time31.setText(ar2.getMintime_gc());
								holder.attendance_item_layout_classsection_img_in31.setImageResource(getRemarkImg(ar2.getRemarkcode_gc()));
				                holder.attendance_item_layout_classsection_status31.setText(ar2.getRemarkcode_gc());
				                if(list2.size()==1){
				                	holder.attendance_item_layout_classsection_record321.setVisibility(View.VISIBLE);
					                holder.attendance_item_layout_classsection_time32.setText("下班没有打卡");
					                holder.attendance_item_layout_classsection_img_in32.setImageResource(R.drawable.attendance_weishuaka);
					                holder.attendance_item_layout_classsection_status32.setText("");
				                }
			                }else if(ar2.getMtype_gc().equals("1")){
			                	holder.attendance_item_layout_classsection_record321.setVisibility(View.VISIBLE);
				                holder.attendance_item_layout_classsection_time32.setText(ar2.getMaxtime_gc());
				                holder.attendance_item_layout_classsection_img_in32.setImageResource(getRemarkImg(ar2.getRemarkcode_gc()));
				                holder.attendance_item_layout_classsection_status32.setText(ar2.getRemarkcode_gc());
				                if(list2.size()==1){
				                	holder.attendance_item_layout_classsection_record311.setVisibility(View.VISIBLE);
									holder.attendance_item_layout_classsection_time31.setText("上班没有打卡");
									holder.attendance_item_layout_classsection_img_in31.setImageResource(R.drawable.attendance_weishuaka);
					                holder.attendance_item_layout_classsection_status31.setText("");
				                }
			                }
							
						}
						else if(p==3){
							holder.item_layout_classsection44.setVisibility(View.VISIBLE);
							holder.attendance_item_layout_classsection_name44.setText(ar2.getOnoffdutyname_gc()+" "+ar2.getStarttime_gc()+"-"+ar2.getEndtime_gc());
							if(ar2.getMtype_gc().equals("0")){
			                	holder.attendance_item_layout_classsection_record411.setVisibility(View.VISIBLE);
								holder.attendance_item_layout_classsection_time41.setText(ar2.getMintime_gc());
								holder.attendance_item_layout_classsection_img_in41.setImageResource(getRemarkImg(ar2.getRemarkcode_gc()));
				                holder.attendance_item_layout_classsection_status41.setText(ar2.getRemarkcode_gc());
				                if(list2.size()==1){
				                	holder.attendance_item_layout_classsection_record421.setVisibility(View.VISIBLE);
					                holder.attendance_item_layout_classsection_time42.setText("下班没有打卡");
					                holder.attendance_item_layout_classsection_img_in42.setImageResource(R.drawable.attendance_weishuaka);
					                holder.attendance_item_layout_classsection_status42.setText("");
				                }
			                }else if(ar2.getMtype_gc().equals("1")){
			                	holder.attendance_item_layout_classsection_record421.setVisibility(View.VISIBLE);
				                holder.attendance_item_layout_classsection_time42.setText(ar2.getMaxtime_gc());
				                holder.attendance_item_layout_classsection_img_in42.setImageResource(getRemarkImg(ar2.getRemarkcode_gc()));
				                holder.attendance_item_layout_classsection_status42.setText(ar2.getRemarkcode_gc());
				                if(list2.size()==1){
				                	holder.attendance_item_layout_classsection_record411.setVisibility(View.VISIBLE);
									holder.attendance_item_layout_classsection_time41.setText("上班没有打卡");
									holder.attendance_item_layout_classsection_img_in41.setImageResource(R.drawable.attendance_weishuaka);
					                holder.attendance_item_layout_classsection_status41.setText("");
				                }
			                }
						}
					}
					p++;
					
				}

			}else{
				//未设置考勤班次 or 自由签？
				holder.item_layout_classsection11.setVisibility(View.GONE);
                holder.attendance_item_layout_classsection_name11.setVisibility(View.GONE);//班次1名称
                holder.attendance_item_layout_classsection_time11.setVisibility(View.GONE);//班次1上班打卡时间
                holder.attendance_item_layout_classsection_status11.setVisibility(View.GONE);//班次1上班打卡状态
                holder.attendance_item_layout_classsection_time12.setVisibility(View.GONE);//班次1下班打卡时间
                holder.attendance_item_layout_classsection_status12.setVisibility(View.GONE);//班次1下班打卡状态
				holder.item_layout_classsection22.setVisibility(View.GONE);
                holder.attendance_item_layout_classsection_name22.setVisibility(View.GONE);//班次2名称
                holder.attendance_item_layout_classsection_time21.setVisibility(View.GONE);//班次2上班打卡时间
                holder.attendance_item_layout_classsection_status21.setVisibility(View.GONE);//班次2上班打卡状态
                holder.attendance_item_layout_classsection_time22.setVisibility(View.GONE);//班次2下班打卡时间
                holder.attendance_item_layout_classsection_status22.setVisibility(View.GONE);//班次2下班打卡状态
				holder.item_layout_classsection33.setVisibility(View.GONE);
				holder.attendance_item_layout_classsection_name33.setVisibility(View.GONE);//班次3名称
                holder.attendance_item_layout_classsection_time31.setVisibility(View.GONE);//班次3上班打卡时间
                holder.attendance_item_layout_classsection_status31.setVisibility(View.GONE);//班次3上班打卡状态
                holder.attendance_item_layout_classsection_time32.setVisibility(View.GONE);//班次3下班打卡时间
                holder.attendance_item_layout_classsection_status32.setVisibility(View.GONE);//班次3下班打卡状态
                holder.item_layout_classsection44.setVisibility(View.GONE);
				holder.attendance_item_layout_classsection_name44.setVisibility(View.GONE);//班次4名称
                holder.attendance_item_layout_classsection_time41.setVisibility(View.GONE);//班次4上班打卡时间
                holder.attendance_item_layout_classsection_status41.setVisibility(View.GONE);//班次4上班打卡状态
                holder.attendance_item_layout_classsection_time42.setVisibility(View.GONE);//班次4下班打卡时间
                holder.attendance_item_layout_classsection_status42.setVisibility(View.GONE);//班次4下班打卡状态
                
    			holder.attendance_item_layout_classsection_record111.setVisibility(View.GONE);
    			holder.attendance_item_layout_classsection_record121.setVisibility(View.GONE);
    			holder.attendance_item_layout_classsection_record211.setVisibility(View.GONE);
    			holder.attendance_item_layout_classsection_record221.setVisibility(View.GONE);
    			holder.attendance_item_layout_classsection_record311.setVisibility(View.GONE);
    			holder.attendance_item_layout_classsection_record321.setVisibility(View.GONE);
    			holder.attendance_item_layout_classsection_record411.setVisibility(View.GONE);
    			holder.attendance_item_layout_classsection_record421.setVisibility(View.GONE);
			}
			
//			mImageFetcher.loadImage(detail.getPic(), holder.imageView);
			
			return convertView;
		}
		
		public int getRemarkImg(String remarkcode){
			int retInt = 0;
			/**
			 * 1000 考勤失败，用户账户不存在
			5000 您所在企业未定义考勤区域，自由签定位成功.
			3000 您所在企业定义了考勤区域，考勤定位成功
			4000 您所在企业定义了考勤区域，您不在考勤区域内，考勤定位失败
			9998 考勤定位成功，参数错误,系统异常,无法检测允许开始、最后打卡时间
			2000 考勤定位成功，考勤时间正常，正常考勤
			6000 考勤定位成功，上班未到考勤时间，加班
			7000 考勤定位成功，上班超过考勤时间，迟到
			8000 考勤定位成功，下班未到考勤时间，早退
			9000 考勤定位成功，下班超过考勤时间，加班
			9999 其他系统异常
			8888 您所在企业定义了考勤区域，但允许自由签，自由签定位成功.
			*/
			int idx = 1000;
			try{
				idx = Integer.parseInt(remarkcode);
				switch(idx){
					case 1000:
						retInt = R.drawable.attendance_1000;
						break;
					case 2000:
						retInt = R.drawable.attendance_2000;
						break;	
					case 3000:
						retInt = R.drawable.attendance_3000;
						break;
					case 4000:
						retInt = R.drawable.attendance_4000;
						break;
					case 5000:
						retInt = R.drawable.attendance_5000;
						break;
					case 6000:
						retInt = R.drawable.attendance_6000;
						break;
					case 7000:
						retInt = R.drawable.attendance_7000;
						break;
					case 8000:
						retInt = R.drawable.attendance_8000;
						break;
					case 8888:
						retInt = R.drawable.attendance_8888;
						break;
					case 9000:
						retInt = R.drawable.attendance_9000;
						break;
					case 9998:
						retInt = R.drawable.attendance_9998;
						break;
					case 9999:
						retInt = R.drawable.attendance_9999;
						break;
				}
			}catch(Exception e){
				e.printStackTrace();
			}
			return retInt;
		}
		
        /**
        249	     * 当列表单元滚动到可是区域外时清除掉已记录的图片视图
        250	     *
        251	     * @param view
        252	     */
        @Override
        public void onMovedToScrapHeap(View view) {
//        	if(flagType){
	            ViewHolder holder = (ViewHolder) view.getTag();
	//        	this.imageViews.remove(holder.avatar);
	//        	this.imageViews.remove(holder.picPhoto);
//	            if(holder!=null && holder.imageView!=null){
////		            holder.imageView.recycle();
//		            holder.imageView = null;
//	            }
//        	}
        }
        
        
        //这个是分组的方法，根据   AttendanceRecord2中的attendancesectionid对 List<AttendanceRecord2>进行分组，最后返回一个Map，键值为attendancesectionid
    	private Map<String, List<AttendanceRecord2>> buildDbEventsMap(List<AttendanceRecord2> spanEventBos) {  
            Map<String, List<AttendanceRecord2>> dbEventMap = new HashMap();  
            List<AttendanceRecord2> tempList = null;
            for (AttendanceRecord2 spanEventBo : spanEventBos) {  
                tempList = dbEventMap.get(spanEventBo.getAttendancesectionid_gc());  
                if (tempList == null) {  
                    tempList = new ArrayList();  
                    tempList.add(spanEventBo);  
                    dbEventMap.put(spanEventBo.getAttendancesectionid_gc(), tempList);  
                }else{  
                	tempList.add(spanEventBo);  
                }  
            }  
            return dbEventMap;  
        }
        
	}
	private static class ViewHolder {
		private HandyTextView item_htv_year;
		private HandyTextView item_htv_monthday;
		
		private LinearLayout item_layout_classsection11;//班次1
		private HandyTextView attendance_item_layout_classsection_name11;//班次1名称
		
		private LinearLayout attendance_item_layout_classsection_record111;
		private HandyTextView attendance_item_layout_classsection_time11;//班次1上班打卡时间
		private HandyTextView attendance_item_layout_classsection_status11;//班次1上班打卡状态
		private ImageView attendance_item_layout_classsection_img_in11;
		private LinearLayout attendance_item_layout_classsection_record121;
		private HandyTextView attendance_item_layout_classsection_time12;//班次1下班打卡时间
		private HandyTextView attendance_item_layout_classsection_status12;//班次1下班打卡状态
		private ImageView attendance_item_layout_classsection_img_in12;
		
		private LinearLayout item_layout_classsection22;//班次2
		private HandyTextView attendance_item_layout_classsection_name22;//班次2名称
		
		private LinearLayout attendance_item_layout_classsection_record211;
		private HandyTextView attendance_item_layout_classsection_time21;//班次2上班打卡时间
		private HandyTextView attendance_item_layout_classsection_status21;//班次2上班打卡状态
		private ImageView attendance_item_layout_classsection_img_in21;
		
		private LinearLayout attendance_item_layout_classsection_record221;
		private HandyTextView attendance_item_layout_classsection_time22;//班次2下班打卡时间
		private HandyTextView attendance_item_layout_classsection_status22;//班次2下班打卡状态
		private ImageView attendance_item_layout_classsection_img_in22;
		
        
		private LinearLayout item_layout_classsection33;//班次3
		private HandyTextView attendance_item_layout_classsection_name33;//班次3名称
		private LinearLayout attendance_item_layout_classsection_record311;
		private HandyTextView attendance_item_layout_classsection_time31;//班次3上班打卡时间
		private HandyTextView attendance_item_layout_classsection_status31;//班次3上班打卡状态
		private ImageView attendance_item_layout_classsection_img_in31;
		private LinearLayout attendance_item_layout_classsection_record321;
		private HandyTextView attendance_item_layout_classsection_time32;//班次3下班打卡时间
		private HandyTextView attendance_item_layout_classsection_status32;//班次3下班打卡状态
		private ImageView attendance_item_layout_classsection_img_in32;
		
		private LinearLayout item_layout_classsection44;//班次4
		private HandyTextView attendance_item_layout_classsection_name44;//班次4名称
		private LinearLayout attendance_item_layout_classsection_record411;
		private HandyTextView attendance_item_layout_classsection_time41;//班次4上班打卡时间
		private HandyTextView attendance_item_layout_classsection_status41;//班次4上班打卡状态
		private ImageView attendance_item_layout_classsection_img_in41;
		private LinearLayout attendance_item_layout_classsection_record421;
		private HandyTextView attendance_item_layout_classsection_time42;//班次4下班打卡时间
		private HandyTextView attendance_item_layout_classsection_status42;//班次4下班打卡状态
		private ImageView attendance_item_layout_classsection_img_in42;
	}
	
	
	public void parserData(final int type) {
		// 去服务器去数据
//		refreshData(type);
		
		switch (type) {
//		case 0:
//			initRefreshView(linkedList);
//			break;
		case 0:
			Message load0 = mHandler2.obtainMessage(LOAD_DATA_FINISH, linkedList);
			mHandler2.sendMessage(load0);
			break;
		case 1:
			Message refresh = mHandler2.obtainMessage(REFRESH_DATA_FINISH,
					linkedList);
			mHandler2.sendMessage(refresh);
			break;
		case 2:
			Message load = mHandler2.obtainMessage(LOAD_DATA_FINISH, linkedList);
			mHandler2.sendMessage(load);
			break;

		default:
			break;
		}
	}
	
	private Handler mHandler2 = new Handler(){
		
		public void handleMessage(android.os.Message msg) {
				switch (msg.what) {
					case 0:
						//没有获取到数据：可能网络问题
//						Toast.makeText(mContext, "没有获取到数据：可能网络问题", Toast.LENGTH_SHORT).show();
						xlistview_count.setText("最近三个月考勤记录0条");
						ptrlv.onRefreshComplete();
						break;
					case REFRESH_DATA_FINISH:
						if(mAdapter!=null){
							List<AttendanceRecord2> newNews=(List<AttendanceRecord2>) msg.obj;
							xlistview_count.setText("最近三个月考勤记录"+newNews.size()+"条");
		//					for(ContactGroup news :newNews){
		//						mAdapter.mList.addFirst(news);
		//					}
							mAdapter.addItemLast(newNews);
							mAdapter.notifyDataSetChanged();
						}
		//				mListView.onRefreshComplete();	//下拉刷新完成
						ptrlv.onRefreshComplete();
						break;
					case LOAD_DATA_FINISH:
						if(mAdapter!=null){
		//					mAdapter.mList.addAll((LinkedList<ContactGroup>)msg.obj);
							List<AttendanceRecord2> newNews=(List<AttendanceRecord2>) msg.obj;
							xlistview_count.setText("最近三个月考勤记录"+newNews.size()+"条");
							mAdapter.addItemLast(newNews);
							mAdapter.notifyDataSetChanged();
						}
		//				mListView.onLoadMoreComplete();	//加载更多完成
						ptrlv.onRefreshComplete();
						break;
		//			case PIC:
		//				mViewPager.setCurrentItem(currentPosition);
		//				break;
					case REFRESH_ROSTER_FINISH:
						if(mAdapter!=null){
							List<AttendanceRecord2> newNews=(List<AttendanceRecord2>) msg.obj;
							xlistview_count.setText("最近三个月考勤记录"+newNews.size()+"条");
		//					for(ContactGroup news :newNews){
		//						mAdapter.mList.addFirst(news);
		//					}
							mAdapter.addItemLast_refresh_roster(newNews);
							mAdapter.notifyDataSetChanged();
						}
		//				mListView.onRefreshComplete();	//下拉刷新完成
						ptrlv.onRefreshComplete();
						break;
					case DELETE_ROSTER_FINISH:
						if(mAdapter!=null){
							List<AttendanceRecord2> newNews=(List<AttendanceRecord2>) msg.obj;
							xlistview_count.setText("最近三个月考勤记录"+newNews.size()+"条");
		//					for(ContactGroup news :newNews){
		//						mAdapter.mList.addFirst(news);
		//					}
							mAdapter.delItemLast_refresh_roster(newNews);
							mAdapter.notifyDataSetChanged();
						}
		//				mListView.onRefreshComplete();	//下拉刷新完成
						ptrlv.onRefreshComplete();
						break;
					case UPDATE_ROSTER_FINISH:
						if(mAdapter!=null){
							List<AttendanceRecord2> newNews=(List<AttendanceRecord2>) msg.obj;
							xlistview_count.setText("最近三个月考勤记录"+newNews.size()+"条");
		//					for(ContactGroup news :newNews){
		//						mAdapter.mList.addFirst(news);
		//					}
							mAdapter.updateItemLast_refresh_roster(newNews);
							mAdapter.notifyDataSetChanged();
						}
		//				mListView.onRefreshComplete();	//下拉刷新完成
						ptrlv.onRefreshComplete();
						break;						
					default:
						break;
				}
		};
	};
	
	//----------------------刷新部分数据----------------------------//
	private static final int LOAD_DATA_FINISH = 10;
	private static final int REFRESH_DATA_FINISH = 11;
	private static final int REFRESH_ROSTER_FINISH = 12;
	private static final int DELETE_ROSTER_FINISH = 13;
	private static final int UPDATE_ROSTER_FINISH = 14;
	
	////////////////////////刷新部分数据//////////////////////////////////////
	private void initRefreshView(LinkedList<AttendanceRecord2> mList){
		mAdapter = new CustomListAdapter(this, mList);
		
		ptrlv = (PullToRefreshListView) this.findViewById(R.id.ptrlvHeadLineNews);
        ptrlv.setOnItemClickListener(mOnAttendanceRecordClick);
//      ptrlv.setOnLongClickListener(mOnContactLongClick);
        ptrlv.setMode(Mode.BOTH);
        ptrlv.setOnRefreshListener(new MyOnRefreshListener2());
//      ptrlv.getRefreshableView().setRecyclerListener();
        ptrlv.setAdapter(mAdapter);
		
	}
	
	class MyOnRefreshListener2 implements OnRefreshListener2<ListView> {

//		private PullToRefreshListView mPtflv;

		public MyOnRefreshListener2() {
//			this.mPtflv = ptflv;
		}

		@Override
		public void onPullDownToRefresh(PullToRefreshBase<ListView> refreshView) {
			// 下拉刷新
//			getContactList(ConstantValues.refresh);
	    	Date dNow = new Date();   //当前时间
	    	Date dBefore = new Date();
	    	Calendar calendar = Calendar.getInstance(); //得到日历
	    	calendar.setTime(dNow);//把当前时间赋给日历
	    	calendar.add(calendar.MONTH, -3);  //设置为前3月
	    	dBefore = calendar.getTime();   //得到前3月的时间

	    	SimpleDateFormat sdf=new SimpleDateFormat("yyyy-MM-dd"); //设置时间格式
	    	String defaultStartDate = sdf.format(dBefore);    //格式化前3月的时间
	    	String defaultEndDate = sdf.format(dNow); //格式化当前时间

	    	System.out.println("前3个月的时间是：" + defaultStartDate);
	    	System.out.println("生成的时间是：" + defaultEndDate);
	    	
	    	getAttendanceList(ConstantValues.refresh,defaultStartDate,defaultEndDate);
		}

		@Override
		public void onPullUpToRefresh(PullToRefreshBase<ListView> refreshView) {
			// 上拉加载
//			getContactList(ConstantValues.load);
	    	Date dNow = new Date();   //当前时间
	    	Date dBefore = new Date();
	    	Calendar calendar = Calendar.getInstance(); //得到日历
	    	calendar.setTime(dNow);//把当前时间赋给日历
	    	calendar.add(calendar.MONTH, -3);  //设置为前3月
	    	dBefore = calendar.getTime();   //得到前3月的时间

	    	SimpleDateFormat sdf=new SimpleDateFormat("yyyy-MM-dd"); //设置时间格式
	    	String defaultStartDate = sdf.format(dBefore);    //格式化前3月的时间
	    	String defaultEndDate = sdf.format(dNow); //格式化当前时间

	    	System.out.println("前3个月的时间是：" + defaultStartDate);
	    	System.out.println("生成的时间是：" + defaultEndDate);
	    	
	    	getAttendanceList(ConstantValues.load,defaultStartDate,defaultEndDate);
		}

	}
	
	
    /**
     * Event simple click on item of the contact list.
     * 单击某联系人，打开chat聊天对话框
     */
//    private class BeemContactListOnClick implements PLA_ListView.OnItemClickListener {
    public class AttendanceRecordListOnClick implements OnItemClickListener {//private
		/**
		 * Constructor.
		 */
		public AttendanceRecordListOnClick( ) {
		}
		/**
		 * {@inheritDoc}
		 */
		@Override
		public void onItemClick(AdapterView<?> arg0, View v, int pos, long lpos) {
			
			AttendanceRecord2 c = (AttendanceRecord2)linkedList.get(pos-1);//pos-1
		    
		}
    }
    
    @Override
    protected void onActivityResult(int requestCode, int resultCode, Intent data) {

    	((MyDialogPopWinSelect)dialog3).onActivityResult(requestCode, resultCode, data);
    }
    
    
  //网络状态 start
  	@Override
  	public void connectionStatusChanged(int connectedState, String reason) {
  		Log.e("MMMMM20140604MMMMMMMMMMMM", "++++++++++++++connectionStatusChanged0++++++++++++");
  		switch (connectedState) {
  		case 0://connectionClosed
  			mHandler3.sendEmptyMessage(0);
  			break;
  		case 1://connectionClosedOnError
//  			mConnectErrorView.setVisibility(View.VISIBLE);
//  			mNetErrorView.setVisibility(View.VISIBLE);
//  			mConnect_status_info.setText("连接异常!");
  			mHandler3.sendEmptyMessage(1);
  			break;
  		case 2://reconnectingIn
//  			mNetErrorView.setVisibility(View.VISIBLE);
//  			mConnect_status_info.setText("连接中...");
  			mHandler3.sendEmptyMessage(2);
  			break;
  		case 3://reconnectionFailed
//  			mNetErrorView.setVisibility(View.VISIBLE);
//  			mConnect_status_info.setText("重连失败!");
  			mHandler3.sendEmptyMessage(3);
  			break;
  		case 4://reconnectionSuccessful
//  			mNetErrorView.setVisibility(View.GONE);
  			mHandler3.sendEmptyMessage(4);

  		default:
  			break;
  		}
  	}
  	Handler mHandler3 = new Handler() {

  		@Override
  		public void handleMessage(android.os.Message msg) {
  			super.handleMessage(msg);
  			switch (msg.what) {
  			case 0:
  				break;

  			case 1:
  				mNetErrorView.setVisibility(View.VISIBLE);
  				if(BeemConnectivity.isConnected(mContext))
  				mConnect_status_info.setText("连接异常!");
  				break;

  			case 2:
  				mNetErrorView.setVisibility(View.VISIBLE);
  				if(BeemConnectivity.isConnected(mContext))
  				mConnect_status_info.setText("连接中...");
  				break;
  			case 3:
  				mNetErrorView.setVisibility(View.VISIBLE);
  				if(BeemConnectivity.isConnected(mContext))
  				mConnect_status_info.setText("重连失败!");
  				break;
  				
  			case 4:
  				mNetErrorView.setVisibility(View.GONE);
  				String udid = "";
  				String partnerid = "";
  				try{
  					udid = mXmppFacade.getXmppConnectionAdapter().getAdaptee().UDID;
  					partnerid = mXmppFacade.getXmppConnectionAdapter().getMService().getPartnerid();
  				}catch(Exception e){
  					e.printStackTrace();
  				}
//  				udidTextView.setText("udid="+udid);
//  				partneridEditText.setText(partnerid);
//  				getContactList();//20141025 added by allen
  				break;
  			case 5:
  				mNetErrorView.setVisibility(View.VISIBLE);
  				mConnect_status_info.setText("当前网络不可用，请检查你的网络设置。");
  				break;
  			case 6:
  				if(mXmppFacade!=null 
//  						&& mXmppFacade.getXmppConnectionAdapter()!=null 
//  						&& mXmppFacade.getXmppConnectionAdapter().getAdaptee()!=null//&& !mXmppFacade.getXmppConnectionAdapter().getAdaptee().isAuthenticated()
//  						&& mXmppFacade.getXmppConnectionAdapter().getAdaptee().isConnected()
//  						&& mXmppFacade.getXmppConnectionAdapter().getAdaptee().isAuthenticated()
  						&& BeemConnectivity.isConnected(mContext)){
  					
  				}else{
  					mNetErrorView.setVisibility(View.VISIBLE);
  					if(BeemConnectivity.isConnected(mContext))
  					mConnect_status_info.setText("网络可用,连接中...");
  				}
  				break;	
  			}
  		}

  	};
  	private BroadcastReceiver mNetWorkReceiver = new BroadcastReceiver() {
          @Override
          public void onReceive(Context context, Intent intent) {
              String action = intent.getAction();  
              if (action.equals(ConnectivityManager.CONNECTIVITY_ACTION)) {  
                  Log.d("PoupWindowContactList", "网络状态已经改变");  
//                  connectivityManager = (ConnectivityManager)getSystemService(Context.CONNECTIVITY_SERVICE);  
//                  info = connectivityManager.getActiveNetworkInfo();    
//                  if(info != null && info.isAvailable()) {  
//                      String name = info.getTypeName();  
//                      Log.d(tag, "当前网络名称：" + name);  
//                      //doSomething()  
//                  } else {  
//                      Log.d(tag, "没有可用网络");  
//                    //doSomething()  
//                  }  
                  if(BeemConnectivity.isConnected(context)){
//                  	mNetErrorView.setVisibility(View.GONE);
//                  	isconnect = 0;
                  	mHandler3.sendEmptyMessage(6);//4
                  }else{
//                  	mNetErrorView.setVisibility(View.VISIBLE);
//                  	isconnect = 1;
                  	mHandler3.sendEmptyMessage(5);
                  	Log.d("PoupWindowContactList", "当前网络不可用，请检查你的网络设置。");
                  }
              } 
          }
  	};
  	
  	private boolean phonestate = false;//false其他， true接起电话或电话进行时 
      /* 内部class继承PhoneStateListener */
      public class exPhoneCallListener extends PhoneStateListener
      {
          /* 重写onCallStateChanged
          当状态改变时改变myTextView1的文字及颜色 */
          public void onCallStateChanged(int state, String incomingNumber)
          {
            switch (state)
            {
              /* 无任何状态时 :说明没有拨打电话的界面的时候，也就是在拨打电话前和挂电话后的情况*/
              case TelephonyManager.CALL_STATE_IDLE:
              	Log.e("================20131216 无任何电话状态时================", "无任何电话状态时");
              	if(phonestate){
              		onPhoneStateResume();
              	}
              	phonestate = false;
                break;
              /* 接起电话时 :至少有一个电话存在、拨出或激活、接听，而没有一个电话在通话或等待的状态*/
              case TelephonyManager.CALL_STATE_OFFHOOK:
              	Log.e("================20131216 接起电话时================", "接起电话时");
              	onPhoneStatePause();
              	phonestate = true;
                break;
              /* 电话进来时 :在通话的过程中*/
              case TelephonyManager.CALL_STATE_RINGING:
//                getContactPeople(incomingNumber);
              	Log.e("================20131216 电话进来时================", "电话进来时");
//              	onBackPressed();
              	onPhoneStatePause();
              	phonestate = true;
                break;
              default:
                break;
            }
            super.onCallStateChanged(state, incomingNumber);
          }
      }
      
      protected void onPhoneStatePause() {
//  		super.onPause();
      	try{
//      		try {
//      		    if (mRoster != null) {
//      			mRoster.removeRosterListener(mBeemRosterListener);
//      			mRoster = null;
//      		    }
//      		} catch (RemoteException e) {
//      		    Log.d("ContactList", "Remote exception", e);
//      		}
  			if (mBinded) {
  				getApplicationContext().unbindService(mServConn);
  			    mBinded = false;
  			}
  			mXmppFacade = null;
      	}catch(Exception e){
      		e.printStackTrace();
      	}
      }
      
      protected void onPhoneStateResume() {
//  		super.onResume();
      	try{
  		if (!mBinded){
//  		    new Thread()
//  		    {
//  		        @Override
//  		        public void run()
//  		        {
  		    mBinded = getApplicationContext().bindService(SERVICE_INTENT, mServConn, BIND_AUTO_CREATE);

//  		        }
//  		    }.start();		    
  		}
//  		if (mBinded){
//  			mImageFetcher.setExitTasksEarly(false);
//  		}
      	}catch(Exception e){
      		e.printStackTrace();
      	}
      }
      
      /*
       * 打开设置网络界面
       * */
      public static void setNetworkMethod(final Context context){
          //提示对话框
          AlertDialog.Builder builder=new AlertDialog.Builder(context);
          builder.setTitle("网络设置提示").setMessage("网络连接不可用,是否进行设置?").setPositiveButton("设置", new DialogInterface.OnClickListener() {
              
              @Override
              public void onClick(DialogInterface dialog, int which) {
                  // TODO Auto-generated method stub
                  Intent intent=null;
                  //判断手机系统的版本  即API大于10 就是3.0或以上版本 
                  if(android.os.Build.VERSION.SDK_INT>10){
                      intent = new Intent(android.provider.Settings.ACTION_WIRELESS_SETTINGS);
                  }else{
                      intent = new Intent();
                      ComponentName component = new ComponentName("com.android.settings","com.android.settings.WirelessSettings");
                      intent.setComponent(component);
                      intent.setAction("android.intent.action.VIEW");
                  }
                  context.startActivity(intent);
              }
          }).setNegativeButton("取消", new DialogInterface.OnClickListener() {
              
              @Override
              public void onClick(DialogInterface dialog, int which) {
                  // TODO Auto-generated method stub
                  dialog.dismiss();
              }
          }).show();
      }
  	//网络状态 end
}
